Jquery Ajax Post中的CORS问题 [英] CORS issue in Jquery Ajax Post

查看:513
本文介绍了Jquery Ajax Post中的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做jquery的ajax post,因此我会调用两个属于不同域的rest服务来执行我的业务逻辑。虽然这样做,我得到一个CORS问题和谷歌引用,我添加了crossDomain:真正我的ajax,现在,这只有在没有在ajax中指定标题(如下),并且如果我添加标题,得到以下错误。请注意。

I am doing ajax post from jquery such that i will call two rest services belonging to different domain to perform my business logic. While doing this, I get a CORS issue and with google references,i added crossDomain: true to my ajax and now, this works completely fine only when there are no headers specified in the ajax (as below) and if i add headers, I get below error. Please advise.

$.ajax({
    method : 'post',
    dataType: 'json',
    crossDomain: true,
    headers : {
        "country" : "us",
    },
    url : 'myurl.do',
    async : true,
    beforeSend : function() {       
    },
    success : function(data) {
        console.log('success', data);               
    },
    error : function(request, status, error) {
        console.log('Error!', status, error, request);
    },
    complete : function() {
        console.log('Completed!!');
    }
});



如果在Ajax中添加标题,错误如下



Error if header is added in Ajax is as follows


错误! errorObject {readyState:0,getResponseHeader:.ajax / jqXHR.getResponseHeader(),getAllResponseHeaders:.ajax / jqXHR.getAllResponseHeaders(),setRequestHeader:.ajax / jqXHR.setRequestHeader(),overrideMimeType:.ajax / jqXHR .overrideMimeType(),statusCode:.ajax / jqXHR.statusCode(),放弃:.ajax / jqXHR.abort(),状态:.Deferred / promise.state(),始终:.Deferred / promise.always(),则:.Deferred / promise.then(),11 more ...}

"Error!" "error" "" Object { readyState: 0, getResponseHeader: .ajax/jqXHR.getResponseHeader(), getAllResponseHeaders: .ajax/jqXHR.getAllResponseHeaders(), setRequestHeader: .ajax/jqXHR.setRequestHeader(), overrideMimeType: .ajax/jqXHR.overrideMimeType(), statusCode: .ajax/jqXHR.statusCode(), abort: .ajax/jqXHR.abort(), state: .Deferred/promise.state(), always: .Deferred/promise.always(), then: .Deferred/promise.then(), 11 more… }


推荐答案

使其成为一项复杂的请求,需要预检选项请求在发出POST请求之前接收CORS权限。

Adding custom headers makes it a complex request that requires a Preflight OPTIONS request to receive CORS permission before the POST request is made.

检查浏览器的开发人员工具Net选项卡。您应该在那里看到OPTIONS请求。

Examine your browser's developer tools Net tab. You should see the OPTIONS request there.

您需要配置服务器以使用为您实际设置的URL设置的访问控制标题进行响应想要。

You need to configure your server to respond to it with the Access-Control headers that you have set up for the URL you are actually wanting.

这篇关于Jquery Ajax Post中的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆