【问题标题】:Isomorphic fetch (REDUX / nodeJs) - POST request with username / password同构提取(REDUX / nodeJs) - 带有用户名/密码的 POST 请求
【发布时间】:2016-11-28 14:27:07
【问题描述】:

我正在使用以下代码从 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){
});

【问题讨论】:

    标签: node.js post redux isomorphic-fetch-api


    【解决方案1】:

    大多数 API 会使用 POST 请求进行身份验证。他们也期望接收数据以验证(用户/密码)。此外,它们通常需要标头中的额外信息,例如指定您发送的数据(用户/密码数据)的格式(例如应用程序/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);
    }; 
    

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2019-08-14
      • 2015-05-28
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多