简体   繁体   中英

XHR Error : Origin http://localhost is not allowed by Access-Control-Allow-Origin

I'm working on an application that uses Spring MVC, and JQuery on the client side. The AJAX call executed by my client (a page hosted on Apache running on port 80) looks like this :

var login = function() {
  $.ajax({
    url: "http://localhost:8080/login",
    type: 'POST',
    data: { key: "value" },
    error: function(jqXHR){console.log("Error");}
  }).done(function(data, textStatus, jqXHR) {
    console.log(jqXHR.responseText);
  });
  return false;
}

And my server (Tomcat running on port 8080) is designed as follows (taking into account the CORS requirements) :

@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public String login(HttpServletResponse response, @RequestBody Map<String,Object> requestParameters){
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", "*");
    response.setHeader("Access-Control-Request-Method","*");
    String value = (String) requestParameters.get("key");
    // Do validation here
    }

And this is the error displayed on the Chrome Console :

XMLHttpRequest cannot load http://localhost:8080/login. Origin http://localhost is not allowed by Access-Control-Allow-Origin. 

Despite setting the Cross Domain headers, why is it that I'm getting this error? Could someone kindly explain what I'm doing wrong here?

Apparently jQuery was fiddling around with my POST parameters weirdly. All I had to do to fix this was enclose the data parameters in a JSON.stringify() .

The modified query looks like :

var login = function() {
  $.ajax({
    url: "http://localhost:8080/login",
    type: 'POST',
    data: JSON.stringify({ key: "value" }),
    error: function(jqXHR){console.log("Error");}
  }).done(function(data, textStatus, jqXHR) {
    console.log(jqXHR.responseText);
  });
  return false;
}

You have to replace the absolute url http://localhost:8080/login with a relative url like /login .

Otherwise, if you don't want to change the url, you can add crossDomain: true to your ajax function which will be the following :

var login = function() {
  $.ajax({
    url: "http://localhost:8080/login",
    type: 'POST',
    data: { key: "value" },
    crossDomain: true;
    error: function(jqXHR){console.log("Error");}
  }).done(function(data, textStatus, jqXHR) {
    console.log(jqXHR.responseText);
  });
  return false;
}

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