可以使用 Axios 的拦截器来给请求头添加 Token:

axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

fetchTaskList() {
  axios.get('http://localhost:8888/task/findAllTask')
      .then(response => {
        this.taskList = response.data;
        this.nextId = response.data.length;
      })
      .catch(error => {
        console.log(error);
      });
}

这样,在请求发送前,会自动给请求头添加 Token。注意,在使用 Axios 之前,需要先引入 Axios:

import axios from 'axios';
如何在 Axios 请求头中添加 Token

原文地址: https://www.cveoy.top/t/topic/ml7z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录