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

查看:117
本文介绍了使用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()方法将简单地返回

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

All requests are having a 500 error response saying that


无法从请求中解析令牌

The token could not be parsed from the request

来自后端。

如何在每个请求中发送授权标头?

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);

第一个参数是URL。

第二个是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天全站免登陆