【问题标题】:Pass token to Authorization header in react native将令牌传递给本机反应中的授权标头
【发布时间】:2020-03-25 19:23:49
【问题描述】:

我对本机反应还很陌生,所以请温柔:)

我需要将一个令牌传递给授权标头 - 这就是我刚才所拥有的,它不起作用:

const auth = new Buffer('username : <SECRETKEYHERE>');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;


fetch('https://example.com/get-token.php', {
  method: 'POST',
  headers: {
    'Authorization': authHeader,
    'Content-Type': 'application/json'
 },
}).then((response) => response.text())
.then((responseText) => {
  alert(responseText);
  console.log(responseText);
})

(注意:上面的 base64 转换按预期工作并返回正确的 base64 键,所以这不是问题)

但是,如果我将 base64 密钥直接放入授权标头中,则请求会按预期工作:

fetch('https://example.com/get-token.php', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic <BASE64KEYHERE>',
    'Content-Type': 'application/json'
 },
}).then((response) => response.text())
.then((responseText) => {
  alert(responseText);
  console.log(responseText);
})

我已经搜索过 SO 并尝试了各种解决方案,但都没有运气,我已经看过主要的解决方案:

Using an authorization header with Fetch in React Native

React native - FETCH - Authorization header not working

如果有人可以帮助我或为我指明正确的方向,我将不胜感激,因为我花了相当多的时间试图让它毫无乐趣地工作。

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

    通常HTTP Basic Authentication header的格式是

    Authorization:Basic <Base64EncodedAuthString>
    

    在哪里

    Base64EncodedAuthString:=<username>:<password>
    

    所以我想知道冒号前后的空格

    const auth = new Buffer('username : <SECRETKEYHERE>');
    

    ,不应该吗

    const auth = new Buffer('username:<SECRETKEYHERE>');
    

    改为?

    另见https://www.rfc-editor.org/rfc/rfc7617#page-5

    【讨论】:

    • 我删除了空白,现在我收到了成功的请求。我应该试过的!哈哈。感谢您的宝贵时间
    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 2013-01-21
    • 2020-07-03
    • 2020-05-10
    • 2018-02-26
    • 2021-07-11
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多