【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource - VueJS请求的资源上没有“Access-Control-Allow-Origin”标头 - VueJS
【发布时间】:2023-03-15 04:44:01
【问题描述】:

我正在开发一个调用外部 API 的 VueJS 应用程序。当我这样做时:

this.$http.get(myAPIurl)
                .then(response => {
                    return response.json();
                })
                .then(data => {
                    console.log(data);
                }); 

我在 chrome 控制台中遇到这 2 个错误。

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

我该怎么做?

【问题讨论】:

标签: cross-domain vue.js same-origin-policy


【解决方案1】:

如果您向与页面所在域不同的域发送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 也很有帮助。

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 2023-03-16
    • 2014-07-30
    • 2016-01-14
    • 2018-12-02
    • 2015-10-30
    • 2019-10-07
    • 2021-09-28
    • 2021-02-23
    相关资源
    最近更新 更多