简体   繁体   English

如何从 JavaScript 中受密码保护的 API 中获取数据?

[英]How to fetch data from password protected API in JavaScript?

I am trying to fetch data from API which needs a username and password to access it.我正在尝试从需要用户名和密码才能访问它的 API 获取数据。 I was able to fetch this data in python using verify=False but was unable to do the same in JavaScript.我能够使用verify=False在 python 中获取此数据,但无法在 JavaScript 中执行相同操作。 I am facing errors related to CORS (Cross-origin resource sharing).我面临与 CORS(跨域资源共享)相关的错误。 Below is the code I am using:下面是我正在使用的代码:

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)
             })

       }

This should print the JSON data present in the API in URL but result in the below errors:这应该打印 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

I tried disabling the CORS in Browser and setting it to no CORS but it did not work.我尝试在浏览器中禁用 CORS 并将其设置为 no CORS 但它不起作用。

You need to disable CORS on the Server, not the Client.您需要在服务器而不是客户端上禁用 CORS。 CORS is a protection mechanism for Servers. CORS 是针对服务器的保护机制。 Here is a short explanation Video about cors.这是关于 cors 的简短解释视频 Setting your mode: 'no-cors' will not help you.设置你的mode: 'no-cors'对你没有帮助。 It actually might make it worse.它实际上可能会使情况变得更糟。

Your Python Code works because the Request does not originate from a "Website" it originates from a Server so no Origin will be set.您的 Python 代码有效,因为请求不是来自“网站”,而是来自服务器,因此不会设置 Origin。 Your Javascript, however, originates from a Browser and the Browser will send the origin for example localhost:8080 so the Server with activated CORS will block it.但是,您的 Javascript 来自浏览器,浏览器将发送来源,例如localhost:8080 ,因此激活了 CORS 的服务器将阻止它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM