DEV Community

Discussion on: Do you know how to use these useful Axios features?

Collapse
 
priya0607jain profile image
Priya Jain

Hi. Can you explain the difference on passing the header object in axios request with config keyword: var config= { 'headers' : { 'key':'value' } } or directly without config keyword: var headers = { 'key':'value' } ??

What difference does it make on using either of the one approaches?

Collapse
 
napoleon039 profile image
Nihar Raote • Edited

config is not a keyword. It is just the name of the object. When you have certain configurations you want to pass with an axios request, you put them all in an object. You can use whatever name you want as the object's name. Let me give a few examples:

var headers = {
    headers: {
        headerName: 'someHeaderValue'
    }
}

axios.post('url', data, headers);

This would work as well. Since axios accepts an object that contains whatever configurations we want, it doesn't care what we name the object. So the following is also valid:

axios.post('url', data, {headers: {headerName: 'someHeaderValue'}});

Even if you only want to pass headers as configuration, you cannot pass simple key:value pairs. This is because the configuration object can also contain many other values.

So using something like this would not be accepted by axios since it is not the proper syntax:

let headers = {
    headerName: 'someHeaderValue'
};

axios.post('url', data, headers);

Finally, the reason I used the name config everywhere is because it clearly explains what the object is and what it contains. And, like how most of the times the primary HTML file is named index.html, the main CSS file is named styles.css, I found that the variable name config is also used a lot for declaring configuration values (even the official docs use it after all).

I hope that helps. Feel free to ask any more questions you may have.😃