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

但是它无法随请求一起发送授权标头。

这是我的代码:

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错误响应

无法从请求解析令牌

从后端。

如何发送授权头与每个请求?你会推荐react的其他模块吗?


当前回答

axios的第二个参数。Post是数据(不是配置)。Config是第三个参数。详情请见:https://github.com/mzabriskie/axios#axiosposturl-data-config

其他回答

如果你想在头中传递令牌后的一些数据,那么试试这段代码

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

你可以在axios中使用拦截器:


axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

更多信息可以在这里找到:https://axios-http.com/docs/interceptors

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。

如果你发送一个带有空数据的post请求,请记住始终将第二个参数设置为空对象或空字符串,如下例所示。例句:axios。Post ('your-end-point-url-here', ", config)

如果你不设置它,axios会假设你传递的第二个参数是一个formData

const config = {
      headers: { Authorization: `Bearer ${storage.getToken()}` }
    };
    axios
      .post('http://localhost:8000/api/v1/get_token_payloads', {}, config)
      .then(({ data: isData }) => {
        console.log(isData);
      })
      .catch(error => {
        console.log(error);
      });

axios的第二个参数。Post是数据(不是配置)。Config是第三个参数。详情请见:https://github.com/mzabriskie/axios#axiosposturl-data-config