ReactJS-在http请求的axios方法中将JWT令牌作为授权传递

问题描述 投票:0回答:1

我有一个应用程序,我们正在生成一个JWT令牌并在下一个api调用中将该令牌传递给Header。作为响应,我应该得到一个密钥。我能够通过postman看到响应。我正在使用ReactJS前端并尝试通过在执行api调用时在Header中传递JWT令牌但面临一些问题来实现相同目的。我的代码 -

getKey() {
    let postData = {
      vin: "5678",
      id: "abc12",
    };

axios({
      method: "post",
      url: "http://localhost:8080/generateKey",
      headers: {
        "Content-Type": "application/json"
      },
      data: postData
    })
      .then(function(response) {
        setKey(response.data.key);
      })
      .catch(function(error) {
        console.log(error);
        getKeyError();
      });
  }

  memberAuth() {
    var self = this;
    axios({
      method: "GET",
      url: "http://localhost:8080/authenticateMember",
      headers: {
        "Content-Type": "application/json",
        "Authorization": localStorage.setItem()
      },
      data: {
        "id":"xyzzy",
        "password":"abc"
      }
    })
      .then(function(response) {
        //to do

  }

我试图在localStorage / SessionStorage中保存生成的令牌(有效30分钟),但不确定这是否正确。有人能告诉我哪里出错了。

javascript reactjs jwt
1个回答
2
投票

创建你的axios的实例,

const agent = axios.create({
  baseURL: config.api_url,
  transformRequest: [transformRequest],
  transformResponse: [transformResponse],
  headers: { 'Content-Type': 'application/vnd.api+json' },
});

然后调用此函数动态设置标头

agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;

然后调用axios实例的方法来进行API调用

agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),
© www.soinside.com 2019 - 2024. All rights reserved.