【问题标题】:CORS GET request in jQueryjQuery中的CORS GET请求
【发布时间】:2017-08-09 21:46:11
【问题描述】:

我正在尝试发出一个应该返回一堆 json 数据的核心请求,但是由于某种原因请求失败。目前我做的代码如下:

$(document).ready(function () {
var url = 'http://test/v/calls';
$.ajax({
    url: url,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Bearer test");
    },
    success: function (json) {
        console.log("Success", json);
    },
    error: function (textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
    }
});

回复如下:

catcher.js:197 OPTIONS http://test/v/calls 401 (Unauthorized)

还有:

XMLHttpRequest cannot load http://test/v/calls. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://some_domain' is therefore not allowed access. The response had HTTP status code 401.

注意:与授权参数相同的 url 在 Postman 中可以正常工作。看不出有什么问题。

【问题讨论】:

    标签: jquery cors


    【解决方案1】:

    您需要在服务器上启用 cors。它在 Postman 中工作是因为 postman 的协议处理跨站点脚本的方式。你的服务器是建立在什么之上的?以及如何将 cors 添加到端点?是您可以从两个问题开始。

    【讨论】:

    • 根据这篇文章,我在 vhost.conf 中添加了:Header set Access-Control-Allow-Origin "*"link。之后我运行了命令ln -sf /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load。我得到的响应仍然是一样的。
    • 我调试了一下,发现了这个:Www-Authenticate:Bearer realm="api"。那是从哪里来的?不应该测试吗?
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 2015-12-15
    • 2013-12-24
    • 2016-12-11
    • 2018-06-07
    • 2018-02-07
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多