Javascript 使用Superagent访问控制获取请求允许源错误
我正在使用superagent(与npm一起安装)从api获取信息。以下是javascript文件中的代码:Javascript 使用Superagent访问控制获取请求允许源错误,javascript,html,node.js,Javascript,Html,Node.js,我正在使用superagent(与npm一起安装)从api获取信息。以下是javascript文件中的代码: const http = require('superagent'); http .get('https://random.dog/woof.json') .end( function(err, res) { console.log(err); console.log(res.body); }); 我可以在终端中通过键入node app.js来测试这一点。控制
const http = require('superagent');
http
.get('https://random.dog/woof.json')
.end( function(err, res) {
console.log(err);
console.log(res.body);
});
我可以在终端中通过键入node app.js来测试这一点。控制台中出现两条消息,首先是null
,然后是{url:'https://random.dog/2d394360-33e1-4c27-9e64-d65a2ab82d5b.jpg“}
,这就是我要找的。然后我使用browserify命令(browserify app.js-o bundle.js
)使我的javascript文件在html文件中可用。以下是我的html文件的代码:
<html>
<head>
</head>
<body>
<h1>Text</h1>
<script src="bundle.js"></script>
</body>
</html>
这一次,他出现了。这似乎是沿着同样的路线。
幸运的是,我有一个小网站,所以我上传了这些html和js文件到服务器上。我也犯了同样的错误。我甚至将.set('Access-Control-Allow-Origin','*')
更改为.set('Access-Control-Allow-Origin','*')http://example.com)
(当然,example.com是我网站的域名)。没有区别。
我决定看看是否可以使用html文件中的javascript发出请求,而不调用任何其他来源。我尝试了以下代码:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var client = new HttpClient();
client.get('http://random.dog/woof.json', function(response) {
console.log(response);
});
并在firefox中打开了新的html文件。我犯了和第一次一样的错误
为什么我会收到这些错误?我可以做些什么来修复这些错误?提前感谢。默认情况下,同一来源策略会阻止对不同域的Ajax请求。允许这种Ajax请求的唯一方法是通过CORS,这要求服务器启用CORS 必须具有
Access Control Allow Origin
头的是服务器,而不是客户端。例如,尝试呼叫https://api.github.com/
而不是https://random.dog/woof.json
,您会发现您可以访问该URL,因为它启用了CORS标题
历史上,JSON-p也被用作同源策略的变通方法,但它通常不如CORS,并且还需要服务器支持
解决此问题的第三种方法是通过用于站点的服务器反向代理远程服务器,以便源匹配。这种方法在某些情况下可以很好地工作,但会带来自身的扩展和安全考虑。您的远程服务器端有哪些功能?它是您自己的API服务器还是什么的?首先,在浏览器中强制执行同源访问控制(它在其他任何地方都不会使用)。而且,要允许浏览器中的其他来源访问站点,服务器本身必须允许。您不能在浏览器客户端上设置任何允许您进入的内容。注意,添加标题(如
访问控制允许原点
)实际上可能会中断CORS访问,否则会触发飞行前的访问-请参阅
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var client = new HttpClient();
client.get('http://random.dog/woof.json', function(response) {
console.log(response);
});