[json] Passing headers with axios POST request

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

var data = {
    'key1': 'val1',
    'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

And it works, but now I have modified my backend API to accept headers.

Content-Type: 'application/json'

Authorization: 'JWT fefege...'

Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.

I am constantly getting 400 BAD Request error.

Here is my modified request:

axios.post(Helper.getUserAPI(), {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'JWT fefege...'
    },
    data
})      
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

Any help is greatly appreciated.

This question is related to json http-headers http-post axios content-type

The answer is


axios.post can recieve accept 3 arguments that last argument can accept a config object that you can set header

Sample code with your question:

var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
        headers: {Authorization: token && `Bearer ${ token }`}
})       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

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);
  });

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)
      })
    }

This might be helpful,

_x000D_
_x000D_
const data = {_x000D_
  email: "[email protected]",_x000D_
  username: "me"_x000D_
};_x000D_
_x000D_
const options = {_x000D_
  headers: {_x000D_
      'Content-Type': 'application/json',_x000D_
  }_x000D_
};_x000D_
_x000D_
axios.post('http://path', data, options)_x000D_
 .then((res) => {_x000D_
   console.log("RESPONSE ==== : ", res);_x000D_
 })_x000D_
 .catch((err) => {_x000D_
   console.log("ERROR: ====", err);_x000D_
 })
_x000D_
_x000D_
_x000D_ Note: All status codes above 400 will be caught in the Axios catch block. Also, headers are optional for the post method in Axios

Blockquote

Blockquote


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

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


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;
});

To set headers in an Axios POST request, pass the third object to the axios.post() call.

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

To set headers in an Axios GET request, pass a second object to the axios.get() call.

const token = '..your token..' 

axios.get(url, {
  headers: {
    'Authorization': `Basic ${token}`
  }
})

Cheers!! Read Simple Write Simple


Or, if you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.

storePropertyMaxSpeed(){
                axios.post('api/property', {
                    "property_name" : 'max_speed',
                    "property_amount" : this.newPropertyMaxSpeed
                    },
                    {headers :  {'Content-Type': 'application/json',
                                'Authorization': 'Bearer ' + this.$gate.token()}})
                  .then(() => { //this below peace of code isn't important 
                    Event.$emit('dbPropertyChanged');

                    $('#addPropertyMaxSpeedModal').modal('hide');

                    Swal.fire({
                        position: 'center',
                        type: 'success',
                        title: 'Nova brzina unešena u bazu',
                        showConfirmButton: false,
                        timer: 1500
                        })
                })
                .catch(() => {
                     Swal.fire("Neuspješno!", "Nešto je pošlo do davola", "warning");
                })
            }
        },

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})
        })

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to http-post

Passing headers with axios POST request How to post raw body data with curl? Send FormData with other field in AngularJS How do I POST a x-www-form-urlencoded request using Fetch? OkHttp Post Body as JSON What is the difference between PUT, POST and PATCH? HTTP Request in Swift with POST method Uploading file using POST request in Node.js Send POST request with JSON data using Volley AngularJS $http-post - convert binary to excel file and download

Examples related to axios

How to post query parameters with Axios? Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check How can I add raw data body to an axios request? Axios Delete request with body and headers? Axios having CORS issue Axios handling errors Returning data from Axios API axios post request to send form data Change the default base url for axios Access Control Origin Header error using Axios in React Web throwing error in Chrome

Examples related to content-type

Passing headers with axios POST request Spring MVC 4: "application/json" Content Type is not being set correctly What are all the possible values for HTTP "Content-Type" header? New lines (\r\n) are not working in email body HTML Input="file" Accept Attribute File Type (CSV) How do you set the Content-Type header for an HttpClient request? Utility of HTTP header "Content-Type: application/force-download" for mobile? Set Content-Type to application/json in jsp file Cannot set content-type to 'application/json' in jQuery.ajax Difference between application/x-javascript and text/javascript content types