簡體   English   中英

使用標頭(包括GUID用戶名和密碼)從API獲取數據

[英]Fetch data from API using headers including GUID Username and Password

我被分配了開發一個依賴於從API檢索車輛庫存數據的網站的任務。 我以前開發過各種API,但我真的沒有這方面的經驗,這個API讓我有點頭疼! 不幸的是,構建API的公司非常可怕且充滿敵意,並且不願意向我提供有關我可能出錯的地方的任何見解。 盡管我懇求!

以下是API指南中包含的內容:

該請求將通過https調用API_COMPANY提供的URL提供。

安全

所有API都希望將以下http安全標頭作為請求的一部分提供。 所有細節都將由API_COMPANY提供。 每個經銷商都有一個獨特的OrganisatinalUnit_UID。

請求

GET
https://theurltotheapi.net/API/vehicles/stockstockListOptionModel.includenewvehicles=true
Accept: application/json
UserName: USERNAME
Password: PASSWORD
OrganisationalUnit_UID: UID
Host: MYWEBSITE.CO.UK
Accept-Encoding: gzip, deflate

我已經嘗試了各種方法來檢索API數據,包括XMLHttpRequest以及下面的Fetch方法。 但我不斷收到控制台日志403錯誤?

<script src="link_to_credentials.js"></script>
<script>
const uri = 'https://theurltotheapi.net/API/vehicles/stock?stockListOptionModel.includenewvehicles=true';

let username = USERNAME;
let password = PASSWORD;
let h = new Headers(); 

h.append('Accept', 'application/json'); 
h.append('Authorization', 'Basic ' + window.btoa(username + ":" + password));
h.append('Accept-Encoding', 'gzip, deflate');
h.append('Host', 'WEBSITE');

let req = new Request(uri, {
method: 'GET',
headers: h,
OrganisationalUnit_UID: GUID,
mode:'no-cors'
});
fetch(req)
    .then ( (response)=>{
    if (response.ok){
        return response.json();
    }else{
            throw new Error('Could not fetch data');    
         }
})
.then( (jsonData) =>{
    console.log(jsonData);
})
.catch ( (err) =>{
    console.log('ERROR : ', err.message);
});
</script>

我期待在控制台中看到JSON車輛庫存數據,但我得到403禁止錯誤 -

無法加載資源:服務器響應狀態為403(禁止)。

您是否嘗試更改身份驗證標頭以表示其示例

他們的例子:

GET https://theurltotheapi.net/API/vehicles/stockstockListOptionModel.includenewvehicles=true
Accept: application/json
UserName: USERNAME
Password: PASSWORD
OrganisationalUnit_UID: UID
Host: MYWEBSITE.CO.UK
Accept-Encoding: gzip, deflate

但是您只傳遞以下標題:

Accept: application/json
Authorization: Basic <user:pass>
Accept-Encoding: gzip, deflate
Host: WEBSITE

嘗試在此行下添加以下代碼h.append('Host', 'WEBSITE');

h.append('UserName', username);
h.append('Password', password);
h.append('OrganisationalUnit_UID', GUID);

並刪除Authorization標頭

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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