Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS jQuery AJAX request

I'm having troubles with an ajax request. I was getting the error

No 'Access-Control-Allow-Origin' header is present on the requested resource.

So what I tried was this jQuery ajax request:

var request = $.ajax({     type: 'GET',     url: url,     dataType: "json",     xhrFields: {         withCredentials: true     } }); request.done(function(data){     console.log(data); });     

But it is still not working. I am still getting the error.

How should I fix this?

like image 349
user6827 Avatar asked Dec 07 '13 14:12

user6827


People also ask

How do I fix a CORS issue in AJAX?

Solution. To resolve this error, update your code to make the AJAX call to the new URL provided by the redirect. For more information, see the MDN article CORS request external redirect not allowed.

How do I create a cross origin AJAX request?

For instance, if sending a request from http://www.example.com, any of the following would be "cross origin": http://mail.example.com (domain differs) https://www.example.com (protocol differs) http://www.example.com:8080 (port differs)

What is cross domain AJAX request?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.


1 Answers

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:* 

or

Access-Control-Allow-Origin:your domain 

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*" 

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*'); 
like image 159
yoyo Avatar answered Oct 13 '22 17:10

yoyo