Axios network error on Cors Post request with status code 200 - http

I use axios to communicate with my own API (not written in NodeJS).
When I post a non simple request axios always goes directly to the catch block displaying a network error in the console, even with 2 successful Http Requests.
Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
There is also a CORS warning about a missing header
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
However it is included in the Options Request!
When I add 'Access-Control-Allow-Origin': '*' in the Axios request headers, the warning is gone, but the browser doesn't fire a Post request after the successful Options request.
For the sake of being complete here are the post request headers.
The code:
postForm = () => {
axios.post("http://127.0.0.1:8080/",
myComplexObj, {
headers: {
//'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
timeout: 15000
}
).then(res => {
console.log(res);
alert('success');
})
.catch(function(error) {
//code always end up here
console.log(error);
/*Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
*/
console.log(error.response); //undefined
console.log(error.response.data); //undefined
}
})
Any help is gladly appreciated.
What I have tried:
Remove the timeout //no change
Remove the Catch block //still no success
Return status code 204 on Options and/or Post requests //no difference

You are confusing because status 200, however, the browser will not allow you to access the response of a CORS request if the Access-Control-Allow-Origin header is missing.
Here are some great articles that explain how CORS works:
https://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Anyway, I think that you are using Django. So, you need add to settings.py:
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'localhost'
)
Or wherever you have the axios code.

Related

How to allow access to a NextJS api route from a different domain?

I have a NextJs with an /api/revalidate route for on-demand cache revalidation.
But I need to call this endpoint from a different domain and I'm getting the following error:
Access to XMLHttpRequest at 'DOMAIN_1/api/revalidate' from origin 'DOMAIN_2' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
How can I set up CORS on an API endpoint for a NextJS app?
Just found out that NextJS has an example about setting up CORS in an API route:
https://github.com/vercel/next.js/tree/canary/examples/api-routes-cors
And also you can use nextjs-cors, which is a wrapper on top of cors:
https://www.npmjs.com/package/nextjs-cors
The code will look something like this:
import NextCors from 'nextjs-cors';
async function handler(req, res) {
// Run the cors middleware
// nextjs-cors uses the cors package, so we invite you to check the documentation https://github.com/expressjs/cors
await NextCors(req, res, {
// Options
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
origin: '*',
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
});
// Rest of the API logic
res.json({ message: 'Hello NextJs Cors!' });
}

Access to fetch has been blocked by CORS policy at Firebase Functions API

I'm working on my project which includes Angular 9 application using firebase functions. I deployed some function, which should update some values on the Firebase Realtime Database. Unfortunately, I encountered a problem with CORS policy if I use my API.
After adding middleware to my express server, where I added these code, the problem still occurs.
app.post('/changeQuantity', permit(), (request: any, response: any) => {
response.status(200).send({ data: { Message: 'Changing order quantity - success.' } });
})
export default function permit() {
return (req: any, _res: any, next: any) => {
_res.setHeader('Access-Control-Allow-Origin', '*');
_res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
next();
};
}
I noticed, that I get this error when frequently requesting API.
Here is the error which server returns:
Access to fetch at [here is a link to my API endpoint] from origin [my origin] has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Did anybody have the same issues with the firebase functions API? Could it be related to frequent requests of my API endpoints from the development environment? Thanks in advance.
Try using response.header to set the CORS properties, like this
app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
next();
});

GET request working on postman but not in browser

I have encountered a strange issue with a GET request that I am stuck on.
I am calling a GET request from my ASP.Net application that works fine in postman but does not hit my userGETReq.onload.
function getUser(username){
userGETReq.open("GET", userURL + "/" + username);
userGETReq.send();
userGETReq.onload = () => {if(userGETReq.status === 200){//cool stuff }}
I am running on a localhost in the browser - the function to start this is being called from a form that returns false.
<form onsubmit="login(this); return false">
POSTMAN
Picture of successful postman response for the GET request
I have other GET requests from the same application that work.
The only difference between this and the other one that works is that it has a 'variable' that gets passed in and has a set route:
[Route("api/User/{username}")]
public List<User> Get(string username)
This is how my CORS is set up
that is the problem
CORS:
EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
Any help would be greatly appreciated!
The waring I am getting:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:56390/api/user/test3. (Reason: CORS request did not succeed).
to resolve CORS issue, you can write another method in service as follows
Every time service call is made, OPTIONS is triggered first to check if the service call is allowed and once the OPTIONS returns allowed, actual method is invoked
//here you can add URL of calling host or the client URL under HEADER_AC_ALLOW_ORIGIN
#OPTIONS
#Path("/yourservice/")
#LocalPreflight
public Response options() {
String origin = headers.getRequestHeader("Origin").get(0);
LOG.info(" In options!!!!!!!!: {}", origin);
if ("http://localhost:4200".equals(origin)) {
return Response.ok()
.header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "GET,POST,DELETE,PUT,OPTIONS")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN, "http://localhost:4200")
.header(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS, "content-type")
.build();
} else {
return Response.ok().build();
}
}

Getting 401 on API but working with postMan

I have this API:
const url = url;
const headers = new Headers({
"Content-Type": "application/json",
"Accept": "application/json", // change to application/javascript for jsonp
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": true,
"access_token": accessToken,
"id_token": idToken,
});
const options = {
method: "GET",
headers: headers,
credentials: "same-origin",
mode: "no-cors"
};
fetch(url, options)
.then(function(response) {
console.log('-working: ',response.json());
})
.catch(function(error) {
console.log('-error: ',error);
});
Having the same API on postMan this works like a charm there but on my code I always get 401 (Unauthorized).
Also if I remove "no-cors" I get a 401 plus CORS issue
I was having the same issue.
My senior said, that CORS is not safe, so first compare the headers of both the requests.
I would suggest you use Wireshark to see the the header that is being sent from both the requests.
Steps(step 3 and 4 is for conveniently spotting your requests):
Install Wireshark.
Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
There will be many requests and responses, close extra applications.
Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by
typing ip.dst==52.187.182.185 by putting the destination address.
Tap on your request made by postman and by your call.
Compare both the headers.
In my case, I was calling the API from my react native app, and the header parameter was getting converted into lowercase automatically.
So, to correct it, I made the parameter in lowercase in backend server.
Play "Spot the difference" between the two windows and find yours.
If this doesn't work, go with setting up CORS.
CORS needed to be added as an additional header on the back end

Angular2 : detect error from HTTP post

I cannot interecept error from http post
a part of my mservice (http post method)
addApplicationLink(applicationLink: ApplicationLink){
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json; charset=utf-8']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});
in my component :
addApplicationLink() {
//todo
this.addNewLink = false;
/* check if must be done after call real rest service */
//this.applicationLinks.push(this.applicationLinkAdd);
this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)
.subscribe(data => {
this.applicationLinks.push(this.applicationLinkAdd)
},
error => {
// handle error
console.error('this an erreor ' + error.status)
}
)
When user tries to add two same applicationlinks , the backend returns an error 409
But when I execute , error.status displays 200 in browser console
I see also in browser console
XMLHttpRequest cannot load http://localhost:7001...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 409.
rem : Http post is made with json , thus there is a prefligth call
Have you an idea to intercept error 409 ?
In fact, your server doesn't send back the CORS header (Access-Control-Allow-Origin' header is missing). This prevent the browser from providing the actual 409 error to the Angular2 application within the browser.
You need to fix first the problem on the server and you will be able to see this 409 error.
For more details about how CORS works, you could have a look at this article:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

Resources