2014-01-29 54 views
0

我有这个小片的代码,我在Firefox便签测试,以获取包含所有当前可用的Ubuntu点击Google Apps的JSON文件:为什么这个XMLHttpRequest在Firefox Scratchpad中工作,但不在本地主机上?

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的话题不少,但似乎并没有帮助我,因为“访问控制允许来源:”酒店要在服务器上设置,对吗?

我还尝试将'withCredentials'标志设置为true ...但它不会更改任何内容。

那么,为什么它使用便笺簿,但不是当我从http://localhost/project/index.html访问它?

这里的响应头,我得到BTW:

"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" 

任何提示,非常感谢......我已经挖周围,试图事情小时,我真的不知道从哪里何去何从

回答

1

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

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

要解决此问题,您必须编写驻留在本地主机上的服务器端脚本,并充当index.htmlsearch.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 
    }); 
}); 
+0

mmhh ......我从一个空的选项卡运行它。但你是对的,当它从一个活动页面的标签运行它会引发错误'阻塞加载混合活动内容“http://search.apps.ubuntu.com/api/v1/search?q=”'所以做你知道另一种方法来获得美味的json吗? :P –

0

我的猜测是,你需要编码请求参数。

所以不是:

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

尝试:

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