Passing headers with axios POST request

后端 未结 9 1886
青春惊慌失措
青春惊慌失措 2020-11-28 20:27

I have written an axios POST request as recommended from the npm package documentation like:

var data = {
    \'key1\': \'val1\',
    \'key2\': \'val2\'
}
ax         


        
9条回答
  •  -上瘾入骨i
    2020-11-28 20:29

    You can also use interceptors to pass the headers

    It can save you a lot of code

    axios.interceptors.request.use(config => {
      if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
    
      const accessToken = AuthService.getAccessToken();
      if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;
    
      return config;
    });
    

提交回复
热议问题