【问题标题】:How do I save JWT response header using fetch?如何使用 fetch 保存 JWT 响应标头?
【发布时间】:2018-01-05 22:51:07
【问题描述】:

我正在使用 React 并使用 fetch 向服务器发送请求:

fetch("http://localhost:8001/api/login", {
    method: 'post',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
    console.log('Request succeeded with JSON response', data);
    console.log(data.headers.toString())
})
.catch(function (error) {
    console.log('Request failed', error);
});

This is chrome inspect, it shows that I get JWT token from server 我的问题是如何在我的代码中访问它?我实际上需要将它保存到一个变量中,真的没有办法做

data.headers.jwt

如果这没有意义,我很抱歉,如果您需要,我可以澄清一下。

【问题讨论】:

  • 我搜索了一些,我认为这可能与这篇文章有关:stackoverflow.com/a/44816592/8608962
  • 是的,服务器需要发送适当的access-control-expose-headers 来公开它们。注意:你说Request succeeded with JSON response 的地方不是 JSON 响应,它是Response 对象
  • 我将 header('access-control-expose-headers'); 添加到服务器文件的开头。我将如何访问 ReactJS 中的标头?
  • 好吧,您需要指定要公开哪些标头 - 然后,使用 data.headers.get('jwt') 访问 jwt 标头
  • 老实说,除非有充分的理由不这样做,否则我会将 jwt 放在响应正文中,而不是响应标头中 - 但是,因为您发布的代码永远不会访问响应正文,很难说将 jwt 添加到响应正文是否适合您的情况

标签: javascript reactjs http-headers fetch


【解决方案1】:

这是您需要的代码。作为奖励,我添加了一些代码来向您展示如何使用响应数据。

fetch("http://localhost:8001/api/login", {
    method: 'post',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
    console.log('My JWT:', response.headers.get('jwt'));
    return response.json();
})
.then(function (data) {
    // Do something with JSON data.
})
.catch(function (error) {
    console.log('Request failed', error);
});

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 2018-07-02
    • 2016-12-21
    • 2021-08-22
    • 1970-01-01
    • 2018-01-27
    • 2016-12-03
    • 2017-05-26
    相关资源
    最近更新 更多