【发布时间】:2016-01-19 07:37:56
【问题描述】:
尝试使用外部 API。
$http({method: 'json', url: url })
.then(function(data){
console.log(data);
}, function(err, code){
console.log(err);
})
我得到的错误是:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
我无法将 API 配置为接受来自不同域的。相反,我尝试使用jsonp。
$http({method: 'jsonp', url: url })
如果我在 chrome 开发工具中检查网络选项卡,我可以看到正确接收的 200 OK 响应和数据。
但 angular 推出:Unexpected token :
这是因为 Angular 需要“json 回调”。无论如何我可以从客户端解决这个问题吗?
【问题讨论】:
-
不。仅使用浏览器无法修复它,您需要一个服务器,在某个地方(不一定是您自己的)来解释 json 并将其转换为 jsonp。
-
或考虑添加 CORS 标头 html5rocks.com/en/tutorials/cors
标签: javascript json angularjs cors