CORS jQuery AJAX request

117,129

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','*');
Share:
117,129
user6827
Author by

user6827

Updated on November 30, 2020

Comments

  • user6827
    user6827 over 3 years

    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?

  • angrymadcat
    angrymadcat over 9 years
    thanks!! especially for the node js code, it works great. Is there any way to set the header by default instead to set it in every post/get handler?
  • Pieter Meiresone
    Pieter Meiresone almost 9 years
  • Lazerbeak12345
    Lazerbeak12345 about 3 years
    I ran into this on an app of mine, and the problem was actually not server side - I was POST ing to the wrong URL entirely.