I'm calling an API with a JWT. When the token expires or when I send an invalid token, I get a 401 in postman, but when I do it in browser, I get a "Network error". And it works when the token is valid.
I use axios to call the API and the error.response is undefined. When I stringify the error object in catch I see something like this:
{
message : 'Network Error',
name : 'Error',
stack : 'Error: Network Error\n at createError (webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15)\n at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:83:14)'
}
I get 200 in the OPTIONS request, but in the main GET request I get the above error. This is probably because of CORS. But I don't know what to change. The Access-Control-Allow-Origins is *.
I don't understand why I don't get the 401 in browser. Can someone please tell me how to fix this?
Screenshot of network tab:
Options:
Your server is probably not setting Access-Control-Allow-Credentials to true to allow origin access to authorized users.
I don't think you actually have a bug. It's just that axios throws on all 4xx responses by default. Try the following:
axios.get("...", { validateStatus(status) { return true; } })
To fix it up, try add other Cross-Origin Resource Sharing (CORS) headers. Check them at
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Related
I've been trying to capture the response of requests through axios response interceptors.
I have a request that requires authorization; and when the authorization token is valid, the request executes successfully and returns the data with no issues.
However, when the token is expired and the server/backend responds with 403; the Network tab in DevTools shows a 403 and axios shows a 0 status code with CORS issue in the Console.
I know it's not CORS because I have a wildcard allowance on it, the request works fine when the token is valid, and the pre-flight for this returns 200.
Screenshots:
Network Tab
Console Tab
This is a bug with AWS Chalice's local environment. You might be using something else that suffers from this. Here's the issue:
With the first request (options), they add access-control-allow-origin, but when the second request fails, they forget to add the header access-control-allow-origin, so it ends up in this awkward situation.
So, it's a CORS issue, but it's confusing because one has it and another doesn't.
So, I have a rest api developed in Express. For authentication, I'm using cookies and to fetch user info I just do a get request to an endpoint that return me user info if its logged in or a 401 (Unauthorized) status code if its not. My concern is about, when I get a 401 status code, the chrome developer console print
Failed to load resource: the server responded with a status of 401
(Unauthorized)
It does not cause any bug in the client, just that It bothers me to see it hah.
Create an interceptor in the HTTP requests and upon received response, use the single line code console.clear(); to clear the console output.
In that way, even if you receive 401 or 403 or any response from server and a console error/warning is auto generated, then it will be auto cleared as well!
I am trying to get weather data from dark sky api and I keep getting a cors error.
Here is my code:
var url = `https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/${lat},${lon}`;
axios.get(url, config).then(response => {
this.setState({
...
})
}).catch(function (error) {
console.log(error);
});
I get an error "XMLHttpRequest cannot load https://api.darksky.net/forecast/febb2871126cd24613f32a79c32d4158/38.5815719,-121.4943996. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://ebcperez.github.io' is therefore not allowed access."
I got a same issue But i solved that
https://www.freecodecamp.org/forum/t/calling-openweathermap-api-is-blocked-due-to-cors-header-access-control-allow-origin-missing/191868
like this :
"https://cors-anywhere.herokuapp.com/http://samples.openweathermap.org/data/2.5/forecast?appid={your_Api_key}"
or https://api.openweathermap.org/data/2.5/forecast?appid=
So i don't know that url will be didn't occur error
Looks like the Darksky API server doesn't allow CORS, so you won't be able to make this request from your browser.
A possible solution would be to issue the API request from your application server, and then just display it on the front end.
Here’s an explanation of why this happens. The tl;dr is to use a CORS proxy for your requests. Prepend https://cors-anywhere.herokuapp.com/ to your API’s URL. https://cors-anywhere.herokuapp.com/http://api.openweathermap.org...
i hope this works for you
In my API if any query fails then what should be the response status code?
Example :
Grade.find({},function(err,grades) {
if (err)
res.status(500).json({error:err,message: 'Somthing went wrong please try again later'});
else
res.status(200).json({grades:grades});
});
Is 500 OK or should it be something else ?
TL;DR A 500 status is the closest thing to a 'one size fits all' error, but you can get into much deeper details.
According to the standards, you have plenty of choices :
5xx Server Error
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
510 Not Extended
You could also create your own 5xx status to differentiate between error types, just try to use numbers that are not defined for anything else.
Or stick to a 500 status and attach the original error code to your result :
res.status(500).json({error:err, code : err.code, message: 'Somthing went wrong please try again later'});
However, before answering with 5xx, you want to make sure that the error doesn't come from the client, by validating the data you receive. If the received data is invalid, use a 400 Bad Request code. If the issue is security related, use a 403 Not Authorized, etc...
According to http status codes you can use 5xx for server error and 4xx for client error.
I would like to know what is best practice with AJAX authentication process.
When authentication is valid I return HTTP header 200 with response "ok"
What HTTP header do I need to send from server if authentication is NOT valid.
Do I need to set HTTP header to code 500 (ERROR)
or leave it on 200 and implement logic which checks response variable?
You don't want to send a 500 error, since that implies an unexpected server-side error that is not caused by the user.
You'll want to read up on the rfc spec for status codes:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
4XX status codes are for client errors, which is where you'll want to be looking. In your case, you could use 401 if authentication failed, and 403 if that user is not allowed to view the resource.
How about returning HTTP401?
You can handle in in AJAX error handler and redirect the whole page to login screen, if it's your requirement.
$.ajax({
statusCode: {
401: function() {
alert("User not logged in");
}
}
});