2016-11-15 76 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); 
};