HLJ 发布于
2018-06-02 23:49:06

vue请求接口数据2种写法

vue请求接口两种方式

第一种


this.$axios.post(url,data).then(res=> {    
    console.log(res)
}, response => {
    console.log(response)
});


第二种


this.$axios.post(url,data).then(res=> {    
    console.log(res)
}


以下代码写在main.js


axios.interceptors.request.use(
  config => {
      // 判断是否存在X-Authorization,如果存在的话,则每个http header都加上token
      if (localStorage.getItem("token")) {  
          config.headers["token"] ="token"+localStorage.getItem("token");
      };
      return config;
  })

  axios.interceptors.response.use(
   res => {
       console.log(res);
       return res;
  },
  error => {
  console.log(error);
  }
)


从上面代码可以看见,第一种写法每次请求接口时都会有请求头和response来抛出异常,第二种方法将请求头和抛出异常返回写在了main.js里,这样每次在请求接口时就少了部分代码 看上去是不是很简洁粗暴呢!

文章来源:原创 转载请标注出处 http://good1230.com/detail/2018-06-02/17.html
最后生成于 2023-06-18 18:28:45
此内容有帮助 ?
0