使用 axios 发送承载令牌 [英] Sending the bearer token with axios

查看:37
本文介绍了使用 axios 发送承载令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 React 应用程序中,我使用 axios 来执行 REST api 请求.

In my react app i am using axios to perform the REST api requests.

但是它无法随请求发送Authorization 标头.

But it's unable to send the Authorization header with the request.

这是我的代码:

tokenPayload() {
  let config = {
    headers: {
      'Authorization': 'Bearer ' + validToken()
    }
  }
  Axios.post( 
      'http://localhost:8000/api/v1/get_token_payloads',
      config
    )
    .then( ( response ) => {
      console.log( response )
    } )
    .catch()
}

此处 validToken() 方法将简单地从浏览器存储中返回令牌.

Here the validToken() method would simply return the token from browser storage.

所有请求都有 500 错误响应,表示

All requests are having a 500 error response saying that

无法从请求中解析令牌

来自后端.

如何随每个请求发送授权标头?你会推荐任何其他带有 react 的模块吗?

How to send the authorization header with each requests? Would you recommend any other module with react?

推荐答案

const config = {
    headers: { Authorization: `Bearer ${token}` }
};

const bodyParameters = {
   key: "value"
};

Axios.post( 
  'http://localhost:8000/api/v1/get_token_payloads',
  bodyParameters,
  config
).then(console.log).catch(console.log);

第一个参数是网址.
第二个是将随您的请求发送的 JSON 正文.
第三个参数是标题(除其他外).这也是 JSON.

The first parameter is the URL.
The second is the JSON body that will be sent along your request.
The third parameter are the headers (among other things). Which is JSON as well.

这篇关于使用 axios 发送承载令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆