{"pageProps":{"post":{"title":"How to set HTTP headers in Axios","excerpt":"Learn 2 different ways to set HTTP headers in Axios","date":"2021-05-25T00:00:00.000Z","slug":"axios-set-headers","author":{"name":"Suraj Sharma","picture":""},"content":"\n
\n\nIn this tutorial, you will learn how you can\n\n1. set HTTP headers in axios, and\n\n2. set global headers to all HTTP requests in axios \n\n
\n
\n\n## Set HTTP Headers\n\n
\n\nYou can pass a `headers` property to the Axios [request config](https://github.com/axios/axios#request-config)\n\nFor example,\n\n```javascript\nconst axios = require('axios').default;\n\n// or\n// import axios from 'axios';\n\naxios({\n\turl: ‘/user’,\n\tmethod: 'post',\n\tHeaders: {\n\tAuthorization: `Bearer ${yourToken}`\n\tContent-Type: ‘application/json’\n}).then((response)=>{\n console.log(response.data);\n});\n\n```\n\n
\n\nwhere the `method` property is set to HTTP `POST` method, and the `headers` property contains one [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header) and one [representation header](https://developer.mozilla.org/en-US/docs/Glossary/Representation_header)\n\n
\n
\n\n## Set Global Default Headers\n\n
\n\nIf you want to set common headers to all HTTP requests, then you use Axios [config defaults](https://github.com/axios/axios#config-defaults) to set headers\n\n
\n\n```javascript\naxios.defaults.headers.common[\"Authorization\"] = `Bearer ${token}`\n```\n\n
\n\nOr you can set common headers to all `POST` requests as\n\n
\n\n```javascript\naxios.defaults.headers.post[\"Content-Type\"] = 'application/json'\n```\n\n
\n
\n\n**Related Solutions**\n\n- [How to submit form data in post request using axios](/blog/axios-post-form-data)\n\n- [How to upload files in React using Axios](/blog/react-upload-file-using-axios)\n\n- [How to handle an error in async await in JavaScript](/blog/error-handling-in-javascript-async-await)\n\n- [How to loop through an array of objects in React](/blog/for-loop-in-react)\n\n- [How to send a delete request in axios](/blog/axios-delete-request)\n\n
\n\n\n\n","coverImage":{"url":"/images/cover-image.png"},"url":"axios-set-headers","hashtags":"#javascript #axios"}},"__N_SSG":true}