axios请求在header请求头加入自定义信息

axios在header请求头加入自定义信息

_this.$axios.post("/api/noticeInfo/notReadNum",data,{
  headers:{
    'userid':sessionStorage.getItem("userId")
  }
}).then(function (res){
  console.log("未读消息为:",res.data)
}).catch(function (error) {
  console.log(error);
  Toast("请求失败!");
});

单独在某一个方法上添加是这样的,但是我们如果要在请求里添加自定义header字段的话,绝对不是某一个方法,而是全部,那么就需要用到请求拦截器了

axios.interceptors.request.use(
  config => {
    // console.log(config)
    // 自定义header信息(比如token)
    // console.log("请求拦截器添加userId-----------",sessionStorage.userId)
    if(!config.headers['userId']){
      config.headers['userId'] = sessionStorage.userId;
    }
    // console.log(config)
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

当然还可以做别的操作,这只是我根据自己的情况写的,参考链接如下:
https://blog.csdn.net/qq_38867237/article/details/90374209

一次axios调用,发送了两次请求(一次为请求方法为option,一次为正常请求)

设置了自定义的header字段之后突然发现一次axios调用,发送了两次请求(一次为请求方法为option,一次为正常请求),很纳闷啊,秉承着有问题找百度的理念,找到了答案

浏览器对复杂跨域请求的处理,在发送真正的请求前, 会先发送一个方法为OPTIONS的预请求(preflight request), 用于试探服务端是否能接受真正的请求,如果options获得的回应是拒绝性质的,比如404\403\500等http状态,就会停止post、put等请求的发出。

有三种方式会导致这种现象:

1、请求方法不是GET/HEAD/POST

2、POST请求的Content-Type并非application/x-www-form-urlencoded, multipart/form-data, 或text/plain

3、请求设置了自定义的header字段

我的Content-Type设置为“application/json;charset=utf-8”并且自定义了header选项导致了这种情况。

参考链接:https://blog.csdn.net/weixin_38958405/article/details/81016246

你可能感兴趣的:(vue.js,javascript,es6,html5)