I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
If you are using Node.js, try it:
More information: CORS on ExpressJS
The easy way is to just add the extension in google chrome to allow access using CORS.
(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.
Or
In Windows, paste this command in run window
this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.
For Ruby on Rails server in
application_controller.rb
, add this: