在ajax中发布时出现Access-Control-Allow-Origin错误

时间:2017-07-30 06:19:33

标签: jquery ajax

$.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'https://your_url.aspx', // the url where we want to POST
        data        : school, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
                    encode          : true
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();

这是我将一些表单数据发布到特定网址的代码,但是我收到以下错误:

POST https://your_url.aspx 500 (Internal Server Error)
send @ jquery-3.2.1.min.js:4
ajax @ jquery-3.2.1.min.js:4
(anonymous) @ magic.js:20
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3
index.html:1 XMLHttpRequest cannot load 
https://your_url.aspx. No 'Access-Control-
Allow-Origin' header is present on the requested resource. Origin 'null' is 
therefore not allowed access. The response had HTTP status code 500.

我四处寻找如何允许access-control-allow-origin并在$ .ajax中使用

beforeSend: function(request){
  request.setHeaderRequest("Access-Control-Allow-Origin","*")
}

稍后在stackoverflow中看到更多响应后,我将setHeaderRequest更改为addHeaderReuest,但即使这样,我也没有看到来自服务器的响应,尽管错误已被删除。控制台显示为空白。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

出现此错误的原因是您尝试从域中搜索另一个域。使用同源策略,我们只能请求存在于同一域中的那些URL。在我们从其他网站获得身份验证之前,浏览器不允许使用跨域请求,通常称为 CORS Access-Control-Allow-Origin 响应标头指示是否可以与具有给定源的资源共享响应。查看文档Access-Control-Allow-Origin