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);
});
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
If you are using Node-red you have to allow CORS in the
node-red/settings.js
file by un-commenting the following lines:If you are using Flask same as the question; you have first to install
flask-cors
Then include the flask cors in your app
A simple app will look like
For more details, you can check the flask documentation
There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same
http://
path withoutwww.
(or access fromhttp://www.
and post to the same path includingwww.
) which the browser considers as another domain when accessing via awww.
path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.