简体   繁体   中英

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?

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','*');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM