[英]How to fetch data from password protected API in JavaScript?
我正在尝试从需要用户名和密码才能访问它的 API 获取数据。 我能够使用verify=False
在 python 中获取此数据,但无法在 JavaScript 中执行相同操作。 我面临与 CORS(跨域资源共享)相关的错误。 下面是我正在使用的代码:
getzuuldata(){
fetch('URL', {
"verify": false,
"mode": 'no-cors',
"auth": ["abcd", "aaaaaaaaa"]
}).then(function (response) {
if (!response.ok) {
console.log('Error with status code' + response.status);
return;
}
response.json().then(function (data) {
var is_failing = data["data"]["result"][0]["value"].slice(-1);
console.log("hello" , is_failing);
});
})
.catch(function (err) {
console.log('Error:' + err)
})
}
这应该打印 URL 中 API 中存在的 JSON 数据,但会导致以下错误:
Access to fetch at 'URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
(index):827 GET url net::ERR_FAILED 401
getzuulData @ (index):827
click_service @ (index):1597
(anonymous) @ d3.min.js:1
(index):842 Error:TypeError: Failed to fetch
我尝试在浏览器中禁用 CORS 并将其设置为 no CORS 但它不起作用。
您需要在服务器而不是客户端上禁用 CORS。 CORS 是针对服务器的保护机制。 这是关于 cors 的简短解释视频。 设置你的mode: 'no-cors'
对你没有帮助。 它实际上可能会使情况变得更糟。
您的 Python 代码有效,因为请求不是来自“网站”,而是来自服务器,因此不会设置 Origin。 但是,您的 Javascript 来自浏览器,浏览器将发送来源,例如localhost:8080
,因此激活了 CORS 的服务器将阻止它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.