簡體   English   中英

如何從 JavaScript 中受密碼保護的 API 中獲取數據?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM