【问题标题】:Why does this XMLHttpRequest work in Firefox Scratchpad but not on localhost?为什么这个 XMLHttpRequest 在 Firefox Scratchpad 中有效,但在 localhost 中无效?
【发布时间】:2014-02-21 05:40:23
【问题描述】:

我有一小段代码,我在 Firefox Scratchpad 中进行了测试,以获取包含所有当前可用的 Ubuntu Click Apps 的 json 文件:

function getHttp(url, callback) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
    if (req.readyState === XMLHttpRequest.DONE) {
        callback(req.responseText);
    }
};
    req.open("GET", url, true);
    req.send();
}

 getHttp("http://search.apps.ubuntu.com/api/v1/search?q=", function(response) {
console.log(response);
});

直接从暂存器运行时,它会正确获取所需的 json。但是,当我将它放在一个小 html 应用程序的 javascript 文件中时,我正在编写它只返回一个空字符串响应。
(页面托管在 xampp 安装上)

我已经对 CORS 的主题进行了很多研究,但它似乎对我没有帮助,因为必须在服务器上设置“Access-Control-Allow-Origin:”属性,对吧?

我还尝试将 'withCredentials' 标志设置为 true...但它不会改变任何东西。

那么为什么它可以与暂存器一起使用,但当我从 http://localhost/project/index.html 访问它时却不行?

这是我得到的响应标头:

"Date: Wed, 29 Jan 2014 12:04:52 GMT

 Server: gunicorn/0.15.0

 Content-Type: application/json

 Expires: Wed, 29 Jan 2014 12:05:52 GMT

 X-Bzr-Revision-Number: 68

 Cache-Control: max-age=60, private

 Content-Length: 29207

 X-Cache: MISS from localhost

 X-Cache-Lookup: MISS from localhost:3128

 Via: 1.0 localhost (squid/3.1.19)

 Strict-Transport-Security: max-age=2592000"

非常感谢任何提示...我已经挖掘并尝试了几个小时,但我真的不知道从这里去哪里

【问题讨论】:

    标签: javascript json xmlhttprequest cors


    【解决方案1】:

    URL http://search.apps.ubuntu.com/api/v1/search?q= 不允许 CORS 请求,因为它没有在响应中发送 Access-Control-Allow-Origin 标头。 不需要withCredentials。

    使用 Scratchpad,您必须尝试在 http://search.apps.ubuntu.com 域上运行代码。如果您尝试在不同的域上运行相同的代码,您将不会得到响应。通过console 运行代码时也是如此。

    要解决这个问题,您必须编写一个驻留在本地主机上并充当index.html 和search.apps.ubuntu.com 之间的代理的服务器端脚本。该脚本将对 URL 进行 HTTP GET 并将响应返回到 index.html。

    getHttp("ubuntuProxy", function(response) {
      console.log(response);
    });
    

    NodeJS 中的脚本

    var http = require('http'),
    options = {host: 'search.apps.ubuntu.com', path: '/api/v1/search?q='}
    
    http.get(options, function(res) {
       var response;
       res.on('data', function (data) {
         response += data;
       });
       res.on('end', function () {
         //set appropriate headers and send the response body
       });
    });
    

    【讨论】:

    • mmhh...我正在从一个空选项卡运行它。但是你是对的,当从一个带有活动页面的选项卡运行它时,它会抛出错误Blocked loading mixed active content "http://search.apps.ubuntu.com/api/v1/search?q=",所以你知道另一种方法来获得那个美味的 json 吗? :P
    【解决方案2】:

    我的猜测是您需要对请求参数进行编码。

    所以而不是:

    req.open("GET", url, true);
    req.send();
    

    试试:

    req.open("GET", encodeURIComponent(url), true);
    req.setRequestHeader("content-type","application/x-www-form-urlencoded");
    req.send();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 2011-03-12
      • 2015-09-12
      • 1970-01-01
      相关资源
      最近更新 更多