2016-11-15 30 views
1

我正在使用下面的代碼從API獲取數據並且工作正常。我有另一個安全的API,它需要用戶名/密碼才能訪問內容,我不確定如何在使用同構提取模塊時傳遞憑證。有人可以幫忙嗎?同構提取(REDUX/nodeJs) - 帶用戶名/密碼的POST請求

我使用這個模塊:https://www.npmjs.com/package/isomorphic-fetch

我需要的用戶名和密碼,通過如下(樣本curl命令)

curl -u admin:hello123 http://test:8765/select?q=* 

代碼:

fetch(
    url 
).then(function (response) { 
    if (response.status != 200) { 
     dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url)) 
    } 
    return response.json(); 
}).then(function (json) { 
    dispatch(setData(json, q)) 
}).catch(function(err){ 
}); 

回答

1

大多數API將使用一個POST請求認證。他們希望接收數據以驗證(用戶/密碼)。另外,它們通常需要額外的信息來指定你發送的數據(用戶/密碼數據)的格式(例如application/json)。你沒有通過任何。請在下面檢查可能有用的東西,但這一切取決於您打算使用的API的期望值(請查看其文檔)。

fetch(url, { 
    method: 'POST', 
    headers: { 
     // Check what headers the API needs. A couple of usuals right below 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
     // Validation data coming from a form usually 
     email: email, 
     password: password 
    } 
}).then(function (response) { 
    if (response.status != 200) { 
     dispatch(setError(response.status + '===>' + response.statusText + '===>' + response.url)) 
    } 
    return response.json(); 
}).then(function (json) { 
    dispatch(setData(json, q)) 
}).catch(function(err){ 
    console.log(err); 
}; 
相關問題