同构获取 (REDUX / nodeJs) - POST 请求用户名/密码

Isomorphic fetch (REDUX / nodeJs) - POST request with username / password

我正在使用下面的代码从 API 取回数据并且工作正常。我有另一个 API 是安全的,需要用户名/密码才能访问内容,我不确定在使用同构获取模块时如何传递凭据。有人可以帮忙吗?

我正在使用这个模块: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){
});

大多数 API 会使用 POST 请求进行身份验证。他们也希望收到数据以进行验证 (user/password)。此外,他们通常需要 header 中的额外信息,例如指定您发送的数据(user/password 数据)的格式(例如 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);
};