在我的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的其他模块吗?


当前回答

您可以一次创建配置,然后在任何地方使用它。

const instance = axios.create({
  baseURL: 'https://example.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

其他回答

你可以在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

下面是axios中设置授权令牌的独特方法。为每个axios调用设置配置并不是一个好主意,您可以通过以下方式更改默认的授权令牌:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

一些API要求承载被写成承载,所以你可以这样做:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

现在您不需要为每个API调用设置配置。现在,授权令牌被设置为每个axios调用。

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

如果你发送一个带有空数据的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);
      });

你可以这样配置头文件:

const headers = {"Content-Type": "text/plain", "x-access-token": token}