在我的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本身带有两个有用的“方法”——拦截器,它们只是请求和响应之间的中间件。如果每个请求都要发送令牌。使用interceptor.request。

我做了一个包来帮助你:

$ npm i axios-es6-class

现在可以使用axios作为类了

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

我的意思是中间件的实现取决于您,或者如果您喜欢创建自己的axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a 这是它来自的中帖

其他回答

以防有人遇到同样的问题。

这里的问题是,当传递没有数据的头时,头的配置将在有效载荷数据中,所以我需要传递null而不是数据,然后设置头的配置。

const config = {
         headers: {
             "Content-type": "application/json",
              "Authorization": `Bearer ${Cookies.get("jwt")}`,
         },
    };    
axios.get(`${BASE_URL}`, null, 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调用设置配置并不是一个好主意,您可以通过以下方式更改默认的授权令牌:

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实例,同时向其中添加拦截器。然后在每次调用中,拦截器将为我将令牌添加到请求头中。

import axios from 'axios';
import { getToken } from '../hooks/useToken';

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
});

axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken();
    const auth = token ? `Bearer ${token}` : '';
    config.headers.common['Authorization'] = auth;
    return config;
  },
  (error) => Promise.reject(error),
);

export default axiosInstance;

下面是我如何在服务文件中使用它。

import { CancelToken } from 'axios';
import { ToolResponse } from '../types/Tool';
import axiosInstance from './axios';

export const getTools = (cancelToken: CancelToken): Promise<ToolResponse> => {
  return axiosInstance.get('tool', { cancelToken });
};

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。