我正在开发一个调用外部API的VueJS应用程序。当我这样做时:
this.$http.get(myAPIurl)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
我在Chrome控制台中收到了这两个错误。
Refused to set unsafe header "Access-Control-Request-Method"
XMLHttpRequest cannot load http://xxxxxx 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:8080' is therefore not allowed access
我该如何解决?
答案 0 :(得分:0)
如果您正在使用XMLHttpRequest到与您的网页不同的域,则您的浏览器会阻止它,因为出于安全原因,它通常允许来自同一来源的请求。当您想要执行跨域请求时,您需要做一些不同的事情。有关如何实现这一目标的教程是 Using CORS 。
当您使用邮递员时,他们不受此政策的限制。引自 Cross-Origin XMLHttpRequest :
常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但它们受到相同原始策略的限制。扩展不是那么有限。扩展可以与其来源之外的远程服务器通信,只要它首先请求跨源权限。
要解决此问题,您的外部API服务器必须通过设置以下标头来支持cors请求:
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
您可以将格式设置为jsonp
,就像在此codepen中一样。 Here讨论了如何将jsonp
与vue-resource一起使用,请参阅此链接中的示例代码:
this.$http.jsonp('https://api.instagram.com/v1/tags/' + this.hash + '/media/recent', {
client_id: 'xxxxxxxxxxxxxxxxxxxxxxxx'
}, function(data){
this.pictures = _map(data.data, this.transFormInstagramModelToLocalModel);
}, {
'jsonp': 'callback'
});
您可以找到有助于讨论的here。