question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

how to override axios.defaults.headers.common for crossdomain requests

See original GitHub issue

In my app which uses X-CSRF-TOKEN in all api requests to MY server, I wanted to use axios to also perform an api GET request to an external server (giphy in this case)

I kept getting this error

Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.

Basically my understanding of this error is that Giphy’s server does NOT want this header to be included

This header is included by default in my axios configuration however. I tried many things to get it to NOT send this header, but nothing worked until I came up with this rather ugly hack:

var self = this;
var axiosCrossDomain = axios;
delete axiosCrossDomain.defaults.headers.common["X-CSRF-TOKEN"];
axiosCrossDomain(apiEndPoint, {
	method: "GET",
	params: {
		api_key: publicKey,
		q: self.query.split(" ").join("+"),
		limit: 50
	}
})
	.then(function(response) {
		self.results = response.data.data;
		self.current_gif = false;
	})
	.catch(function(error) {
		console.log(error);
	});

This works… it was not required for me to make a copy of axios like I did but since my app is a SPA I wanted to make sure that I was not removing the X-CSRF-TOKEN from all instances of axios

But surely there must be another, better way to do this?

Anyone know?

Thanks

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:4
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

15reactions
agm1984commented, Sep 18, 2019

Here is my solution. This allows me to rely on the default Laravel implementation for default headers in bootstrap.js and then every time I make an external API request, I use this:

// temporarily wipe 'X-CSRF-TOKEN' header for Google CORS
const instance = axios.create();
instance.defaults.headers.common = {};
instance.defaults.headers.common.accept = 'application/json';

const { data } = await instance.get(generatedUrl);

generatedUrl is of course proprietary to your app, like https://www.com/api

The absolute trick is that, in my case, Google’s API requires that the 'X-CSRF-TOKEN' header be absent, so you can’t simply set it to undefined. So after dealing with this problem off and on for several weeks, my above solution is what I have ended up with.

The trick is to not even go down a path of trying to temporarily mutate axios.defaults.headers because you will encounter horrific async issues if you make an external API call while a page loads and a user on your site submits a form that makes an internal API call before your external API call has responded back and restored the axios.defaults back to normal.

If the axios.defaults were mutated during that time, you will of course experience the full wrath of shared mutable state. Fire up a separate axios instance, and make your external API calls using that.

Relevant docs are likely here if you want to investigate other trinkets: https://github.com/axios/axios

// function signature
const config = {};
const instance = axios.create(config)

NOTE: You cannot assign the headers in the config object. You must mutate them afterwards with:

instance.defaults.headers.common = {};
instance.defaults.headers.common.accept = 'application/json';
6reactions
emilyemorehousecommented, Feb 8, 2018

Just to make sure I understand, at some point you’re adding the X-CSRF-TOKEN header to your global configuration, correct? That header shouldn’t be included as one of the default headers out of the box.

Otherwise, I would suggest using multiple instances in order to separate your API endpoints, like this:

var instance = axios.create({
    headers: {
        common: {
            'X-CSRF-TOKEN': 'totallyfaketoken',
        },
    },
});

This supports the full configuration as well, in case there’s anything else you want to include. If you are using any other forms of configuration (global, etc.), I recommend checkout out the docs on config precedence.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using Axios to set request headers - LogRocket Blog
Learn different ways Axios can be used to set request headers for API calls. ... axios.defaults.headers.common['Authorization'] = `Bearer ...
Read more >
Axios having CORS issue - Stack Overflow
I'm sending data from a react application to a golang server. Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*") , ...
Read more >
Request to api from axios (cross domain) (CORS) error
I'm try to fetch data from bank api with AXIOS and heve an error. ... check: No 'Access-Control-Allow-Origin' header is present on the...
Read more >
Config Defaults | Axios Docs
You can specify config defaults that will be applied to every request. ... 'https://api.example.com'; axios.defaults.headers.common['Authorization'] ...
Read more >
Complete Guide to Axios HTTP Client - Reflectoring
headers : HTTP headers received in the API response; config: config sent to the axios instance for sending the request; request: Request that ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found