当前位置:   article > 正文

把token存在请求头里,使用Axios来设置请求头(headers)的方法_axios.post 加入header token

axios.post 加入header token

传递一个对象参数

诸如post() 和get() 等Axios方法使我们能够在请求中附加头信息,方法是将头信息对象作为GET

请求的第二个参数和POST请求的第三个参数

这段代码为所有请求设置了授权头信息  

注意    axios.defaults.headers.common['Authorization']里面是有 ' ' 引号的
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')`;
  1. 实际案例:在request.js里面封装的axios方法里的请求拦截器里
  2. import axios from 'axios';
  3. import { ElMessage, ElMessageBox } from 'element-plus';
  4. import store from '@/store';
  5. import { localStorage } from '@/utils/storage';
  6. // 创建axios实例
  7. const service = axios.create({
  8. baseURL: import.meta.env.VITE_APP_BASE_API, //VITE_APP_BASE_API开发环境
  9. timeout: 50000, // 请求超时时间:50s
  10. headers: { 'Content-Type': 'application/json;charset=utf-8' },
  11. });
  12. // 请求拦截器
  13. service.interceptors.request.use(
  14. (config) => {
  15. console.log(config)
  16. if (!config.headers) {
  17. throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
  18. }
  19. const { isLogin, tokenObj } = toRefs(store.user.useUserStore());
  20. //拿到存在本地里的tokenObj,
  21. if (isLogin.value) {
  22. // 授权token认证 设置token
  23. config.headers['token'] = tokenObj.value.token;
  24. }
  25. return config;
  26. },
  27. (error) => {
  28. return Promise.reject(error);
  29. },
  30. );
  31. //响应拦截器
  32. // 导出实例
  33. export default service;
单个请求

POST和GET请求分别用于创建或检索一个资源。下面是一些一次性或单个请求的例子。

首先,我们声明config 对象,其中包含headers 对象,它将在提出请求时作为一个参数提供。我们还声明了一个api endpoint 和一个data 对象。

  1. const config = {
  2. headers:{
  3. header1: value1,
  4. header2: value2
  5. }
  6. };
  7. const url = "api endpoint";
  8. const data ={
  9. name: "Jake Taper",
  10. email: "taperjake@gmail.com"
  11. }

我们可以使用GET请求从API端点url 检索config 对象。

  1. axios.get(url, config)
  2. .then(res=> console.log(res))
  3. .catch(err=> console.log(err))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/715517
推荐阅读
相关标签
  

闽ICP备14008679号