可以使用 Axios 的 interceptors 来实现在请求头中添加 Token。代码如下:

fetchTaskList() {
  const token = localStorage.getItem('token');
  axios.interceptors.request.use(
    config => {
      config.headers.Authorization = `Bearer ${token}`;
      return config;
    },
    error => Promise.reject(error)
  );
  axios.get('http://localhost:8888/task/findAllTask')
      .then(response => {
        this.taskList = response.data;
        this.nextId = response.data.length;
      })
      .catch(error => {
        console.log(error);
      });
}

这里使用了 Axios 的 interceptors 来对请求进行拦截和处理。首先获取存储在 localStorage 中的 Token,然后在请求头中添加 Authorization 字段,值为 Bearer 加上 Token。这样在发送请求的时候就会自动带上 Token,以便后端进行身份验证。

如何在请求头中添加 Token - Axios 拦截器

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

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