简体   繁体   中英

Cross Origin ajax “POST” request failing

I have a webservice(REST) running on localhost:8080, to call the webservice I use this jquery code:

jQuery.ajax({
        type: "POST",
        url: "http://localhost:8080/user/register",
        data: '{"name": "' + name + '","email": "' + email + '","password": "' + password + '"}',
         beforeSend: function(x) {
              if(x && x.overrideMimeType) {
               x.overrideMimeType(jsonMimeType);
              }
             },
        dataType:"jsonp",
        Accept : "application/json",
        contentType: "application/json",
        success: registerUser_success_callback,
        error: registerUser_error_callback
    });

When I try to call this javascript from the same domain(ie localhost:8080), it work just like a charm!. Here is the screen shot of the same: 在此处输入图片说明

But when I try to access the same from a different domain(ie localhost:80), it fails, and surprisingly instead of a POST, it sends out a GET and I also get a log in my server's log file, saying that the GET method not supported for REST resource. Here is the screen of the same: 在此处输入图片说明

From what I have read on internet(especially here , great article!), cross domain request should first send out an OPTIONS request(which is cached for later usage.) What is going wrong in my case?

I have tried calling the rest service with same parameters using FireFox's plugin RESTClient, I was able call the rest service(POST method) successfully, so this mostly is the issue with ajax part.

Help me resolve this cors hell! and do lemme know if I need to share any more details on this.

PS: After @A. Wolff Suggested, I changed the data tyoe from jsonp to json, now my browser sends out OPTIONS, but after that it doesn't send the actual POST request!!!

Well, some more digging and I found the solution to this!

After the change A. Wolff suggested, browser was sending out an OPTIONS request and was receiving a 200 response, but after that actual POST request was not being sent to the server.

Problem was, if you send any specific headers, "Content-Type" in my case, server has to add that header in "Access-Control-Allow-Headers" field of the response(response of OPTIONS request). I changed my server side code to populate that field in the response header, and VOILA!

Hope this will be helpful to others, too!

Happy Coding.

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