Passing headers with axios POST request

后端 未结 9 1859
青春惊慌失措
青春惊慌失措 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条回答
  • 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;
    });
    
    0 讨论(0)
  • 2020-11-28 20:36

    Interceptors

    I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:

    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    0 讨论(0)
  • 2020-11-28 20:37

    We can pass headers as arguments,

      onClickHandler = () => {
        const data = new FormData() 
        for(var x = 0; x<this.state.selectedFile.length; x++) {
          data.append('file', this.state.selectedFile[x])
        }
    
        const options = {
          headers: {
              'Content-Type': 'application/json',
          }
        };
        
        axios.post("http://localhost:8000/upload", data, options, {
          onUploadProgress: ProgressEvent => {
            this.setState({
              loaded: (ProgressEvent.loaded / ProgressEvent.total*100),
            })
          },
        })
          .then(res => { // then print response status
            console.log('upload success')
          })
          .catch(err => { // then print response status
            console.log('upload fail with error: ',err)
          })
        }
    
    0 讨论(0)
  • 2020-11-28 20:40

    Shubham answer didn't work for me.

    When you are using axios library and to pass custom headers, you need to construct headers as an object with key name "headers". The headers key should contain an object, here it is Content-Type and Authorization.

    Below example is working fine.

        var headers = {
            'Content-Type': 'application/json',
            'Authorization': 'JWT fefege...' 
        }
        axios.post(Helper.getUserAPI(), data, {"headers" : headers})
    
            .then((response) => {
                dispatch({type: FOUND_USER, data: response.data[0]})
            })
            .catch((error) => {
                dispatch({type: ERROR_FINDING_USER})
            })
    
    0 讨论(0)
  • 2020-11-28 20:44

    Here is a full example of an axios.post request with custom headers

    var postData = {
      email: "test@test.com",
      password: "password"
    };
    
    let axiosConfig = {
      headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          "Access-Control-Allow-Origin": "*",
      }
    };
    
    axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
    .then((res) => {
      console.log("RESPONSE RECEIVED: ", res);
    })
    .catch((err) => {
      console.log("AXIOS ERROR: ", err);
    })

    0 讨论(0)
  • 2020-11-28 20:47

    When using axios, in order to pass custom headers, supply an object containing the headers as the last argument

    Modify your axios request like:

    const headers = {
      'Content-Type': 'application/json',
      'Authorization': 'JWT fefege...'
    }
    
    axios.post(Helper.getUserAPI(), data, {
        headers: headers
      })
      .then((response) => {
        dispatch({
          type: FOUND_USER,
          data: response.data[0]
        })
      })
      .catch((error) => {
        dispatch({
          type: ERROR_FINDING_USER
        })
      })
    
    0 讨论(0)
提交回复
热议问题