【问题标题】:CORS request with Ajax/Javascript/Django使用 Ajax/Javascript/Django 的 CORS 请求
【发布时间】:2016-11-01 14:25:32
【问题描述】:

我想向谷歌发出 CORS 获取请求(只是一个例子。我实际上正在访问一个返回 json 数据的网站)。下面是我的ajax代码:

$.ajax({
    url: "https://www.google.com",
    type: "get",
    dataType: "json",
    crossDomain: true,
    success: function(data, textStatus) {
        alert ("success" + data);
    },
    error: function(data, textStatus) {
        alert ("fail" + data);
    }
})

使用上面的代码我得到了这个错误:

XMLHttpRequest cannot load https://www.google.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sdlweb-dev:1234' is therefore not allowed access. The response had HTTP status code 405.

我尝试添加类似的代码

        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "X-Requested-With,content-type",
            "Access-Control-Allow-Credentials": true
        }

但仍然出现同样的错误。

我尝试将 dataType 从“json”更改为“jsonp”。这种方式发送请求,但由于响应不是jsonp,我得到另一个错误:

Uncaught SyntaxError: Unexpected token <

如果不修改服务器端(我的意思是我发送 get 请求的 url,因为我无权访问它),我可以发送 CORS 请求吗?

感谢任何帮助!!!

谢谢,

【问题讨论】:

    标签: javascript ajax django xmlhttprequest cors


    【解决方案1】:

    必须有权访问服务器代码才能允许 CORS 请求。

    您显示的标头应该是在响应中发回的标头,而不是在请求中。

    【讨论】:

    • 谢谢!服务器,你的意思是我试图访问的服务器,对吧? (不是我托管我的网站的服务器)
    • 另外,我可以通过将 dataType 设置为“jsonp”来获得响应。但是由于返回的数据类型不是“jsonp”,有没有办法以某种方式包装它并获取内容?
    • @Feiiiiiiiiiiiii 回答您的第一条评论:是的。回答你的第二个:不。
    猜你喜欢
    • 2017-05-05
    • 2015-02-27
    • 2012-12-20
    • 2015-12-15
    • 2013-12-24
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多