跨源ajax“ POST”请求失败

buch11

我有一个运行在localhost:8080上的webservice(REST),要使用以下jquery代码来调用该webservice:

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
    });

当我尝试从相同的域(即localhost:8080)调用此javascript时,它就像一个吊饰一样工作!这是相同的屏幕截图:在此处输入图片说明

但是,当我尝试从其他域(即localhost:80)访问相同文件时,它失败了,令人惊讶的是,它发出了GET消息,而不是POST消息,而且我还在服务器的日志文件中得到了一条日志,说GET REST资源不支持该方法。这是相同的屏幕:在此处输入图片说明

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!!!

buch11

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

在更改A. Wolff建议之后,浏览器正在发送OPTIONS请求并收到200响应,但是在该实际POST请求未发送到服务器之后。

问题是,如果在我的情况下发送任何特定的标头“ Content-Type”,则服务器必须在响应(OPTIONS请求的响应)的“ Access-Control-Allow-Headers”字段中添加该标头。我更改了服务器端代码,以在响应标头中填充该字段,然后VOILA!

希望这对其他人也有帮助!

编码愉快。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章