如何在Axios中实现setRequestHeader函数

时间:2018-06-14 14:41:04

标签: jquery ajax axios

所以我在这里有一个ajax调用:

$.ajax({
   url: "https://api.spotify.com/v1/search?q=tania%20bowra&type=artist",
   type: "GET",
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
   success: function(data) { 
     // Do something with the returned data
     console.log(data);
   }
});

我试图在axios esp中将其转换为beforeSend: function....部分,但我不能,也不知道该怎么做。

我最后接到了这个电话:

   axios
      .get("https://api.spotify.com/v1/search?q=tania%20bowra&type=artist")
      .then(function(response) {
        console.log("here is the response >>>", response);
      })
      .catch(function(error) {
        console.log(error);
      });

关于如何在axios中实现这一点的任何想法:

 beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},

它究竟是做什么的?对不起新手在这里。

1 个答案:

答案 0 :(得分:1)

您可能想要使用request interceptor

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    config.headers["Authorization"] = `Bearer ${token}`;
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

这将允许您拦截所有请求(在它们被发送之前),并修改其配置:

config.headers["Authorization"] = `Bearer ${token}`;

或者,对于全局标题,您可以使用以下内容:

axios.defaults.headers.common['Authorization'] = "Bearer " + token;

我希望这有帮助!