CORS jQuery AJAX request

2020-01-23 07:31发布

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?

1条回答
▲ chillily
2楼-- · 2020-01-23 07:52

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','*');
查看更多
登录 后发表回答