comiventor
comiventor

Reputation: 4122

unable to set header in axios

I am unable to set headers via axios e.g. content-type as application/json. There is no exception thrown by axios but the request gets a "415 Unsupported Media Type" response in browser. Any clues where I am erring?

Following is the code -

I tried 2 approaches.

Approach 1 -

import axios from 'axios';
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.get(url).then(
  response => this.loadData(response)).catch(
  (error) => this.showError(error));

Approach 2 -

let config = {
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json"
    }
};
axios.get(url, config).then(
      response => this.loadData(response)).catch(
      (error) => this.showError(error));

Upvotes: 2

Views: 8509

Answers (1)

Dez
Dez

Reputation: 5838

You are getting that error because you are not setting the Accept header with the proper content type you expect the response from the server should be.

To avoid that, for example, you can create an instance of Axios (to later import it everywhere you do Axios calls in your React.js app) where you can set up the default headers of all the calls that you will do with Axios. For example:

import axios from 'axios';

const instance = axios.create({
  baseURL: [YOUR BASE URL],
  timeout: 5000,
  headers: {
    'Accept-Version': 1,
    'Accept': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json; charset=utf-8',
  },
});

export default instance;

Thus all the calls you do will have the proper headers and you won't have to worry about them being properly set. I also assume you are just going to work with json body requests and responses.

Upvotes: 4

Related Questions