【发布时间】:2020-06-12 09:12:05
【问题描述】:
我已经开始构建一个 Vue.js 网站,使用 AWS Amplify 作为后端。
在其中一个页面中,我需要访问一个外部 url 地址,从中获取响应,并查看对用户的响应。
重要的是,该网址没有链接到我的网站,与我无关。它完全是外部的,不受我的控制。
我曾多次尝试使用多种方法访问该网址,但到目前为止,我每次尝试访问该网址时都会收到以下错误消息:
:8080/#/myPage:1 Access to XMLHttpRequest at 'https://~URL~?~DATA~' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js?b50d:178 GET https://~URL~?~DATA~ net::ERR_FAILED
(我用https://~URL~?~DATA~替换了真实的url,用myPage替换了文件名)。
当我尝试打印从函数接收到的错误时。我收到以下消息:
myPage.vue?3266:161 Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:83)
当我尝试使用浏览器(Google Chrome)访问该网址时,它运行良好且没有任何问题。它没有要求我进行任何类型的身份验证或类似的事情。
我也尝试过使用 Postman,它工作得很好。
我只在使用我的 Vue.js 网站时遇到过这个问题。
当我从 localhost 运行网站以及在主机上运行它时(使用 AWS Amplify 托管无服务器网站 - S3 存储桶),就会出现此问题。
当网站不在 localhost 上运行时,我仍然会收到相同的错误消息。
以下是我尝试访问网址的一些方法:
-
Axios
var config = { method: 'get', url: 'https://~URL~?~DATA~', headers: { 'Access-Control-Allow-Credentials': true } }; axios(config) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); -
获取
var requestOptions = { method: 'GET', redirect: 'follow' }; fetch("https://~URL~?~DATA~", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); -
XHR
var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function() { if(this.readyState === 4) { console.log(this.responseText); } }); xhr.open("GET", "https://~URL~?~DATA~"); xhr.send(); -
请求
var request = require('request'); var options = { 'method': 'GET', 'url': 'https://~URL~?~DATA~', 'headers': { } }; request(options, function (error, response) { if (error) throw new Error(error); console.log(response.body); });
我真的需要你的帮助,因为到目前为止我在整个网络上都找不到任何解决方案。
【问题讨论】:
-
浏览器不允许对其他域的 xhr 请求,除非外部站点指定访问控制标头,因为安全原因。由于该网站不受您的控制,您要么需要使用浏览器插件禁用 cors(如果您的应用供公众使用,则不可行)或让网站所有者允许您的域访问。
标签: javascript vue.js header xmlhttprequest aws-amplify