{"id":6965,"date":"2023-01-12T01:07:06","date_gmt":"2023-01-12T01:07:06","guid":{"rendered":"https:\/\/www.ardorsys.com\/blog\/?p=6965"},"modified":"2023-01-12T04:55:31","modified_gmt":"2023-01-12T04:55:31","slug":"enabling-cors-in-axios-a-step-by-step-guide-for-making-cross-origin-requests-in-javascript","status":"publish","type":"post","link":"https:\/\/www.ardorsys.com\/blog\/enabling-cors-in-axios-a-step-by-step-guide-for-making-cross-origin-requests-in-javascript\/","title":{"rendered":"Enabling CORS in Axios: A Step-by-Step Guide for Making Cross-Origin Requests in JavaScript"},"content":{"rendered":"<p>As a developer, you might have the questions about how to create cross-origin requests in javascripts. There are several ways to make HTTP <a href=\"https:\/\/www.ardorsys.com\/blog\/javascript-es6-cheat-sheet-2021\/\">requests in JavaScript<\/a>, but the most common way is to use the <code>XMLHttpRequest<\/code> object, which is built into most web browsers.<\/p>\n<p>Here&#8217;s an example of how you might use the <code>XMLHttpRequest<\/code> object to make a GET request to a website:<\/p>\n<pre lang=\"javascript\" escaped=\"true\">var xhr = new XMLHttpRequest();\r\nxhr.open(\"GET\", \"https:\/\/www.example.com\");\r\nxhr.send();\r\n\r\n<\/pre>\n<p>You can also use the <code>fetch<\/code> function to make requests in modern browsers which is a promise based function.<\/p>\n<p>Here&#8217;s an example of how you might use the <code>fetch<\/code> function to make a GET request to a website:<\/p>\n<pre lang=\"javascript\" escaped=\"true\">fetch('https:\/\/www.example.com')\r\n  .then(response =&gt; response.text())\r\n  .then(data =&gt; {\r\n    \/\/ do something with the data\r\n  });\r\n\r\n<\/pre>\n<p>You can also use third-party libraries such as <strong>axios, superagent, and jQuery.ajax<\/strong> to make http requests.<\/p>\n<p>Here&#8217;s an example of how you might use the axios library to make a GET request to a website:<\/p>\n<pre lang=\"javascript\" escaped=\"true\">axios.get('https:\/\/www.example.com')\r\n  .then(response =&gt; {\r\n    \/\/ do something with the data\r\n  });\r\n\r\n<\/pre>\n<p>Please note that for making request to CORS enabled server, you need to configure the headers to allow the request from your origin.<\/p>\n<p>To enable CORS (Cross-Origin Resource Sharing) in axios, you can configure the headers of the request to include the <code>Access-Control-Allow-Origin<\/code> field, along with any other required fields.<\/p>\n<p>To set headers for every request you can use the <code>defaults<\/code> property of <code>axios<\/code><\/p>\n<pre lang=\"javascript\" escaped=\"true\">axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';\r\n<\/pre>\n<p>or you can use <code>headers<\/code> property while sending the request<\/p>\n<pre lang=\"javascript\" escaped=\"true\">axios({\r\n  method: 'get',\r\n  url: 'https:\/\/example.com',\r\n  headers: {\r\n    'Access-Control-Allow-Origin': '*',\r\n    \/\/ any other headers\r\n  }\r\n});\r\n\r\n<\/pre>\n<p>You can also use <code>axios.create<\/code> method to create an instance with a specific config, then you can use this instance to make all requests<\/p>\n<pre lang=\"javascript\" escaped=\"true\">const instance = axios.create({\r\n  headers: {'Access-Control-Allow-Origin': '*'}\r\n});\r\n\r\ninstance.get('https:\/\/example.com')\r\n<\/pre>\n<p>Please note that the above code is only enabling the CORS on the client-side, the server needs to set the proper headers to allow the request, otherwise the browser will block the request. Also setting <code>Access-Control-Allow-Origin<\/code> to <code>*<\/code> means allowing any origin to access your server.<\/p>\n<h3><strong>How To handle errors in axios:<\/strong><\/h3>\n<p>When making HTTP requests with <a href=\"https:\/\/www.ardorsys.com\/blog\/array-methods-filter-find-map-reduce-every-and-some-in-javascript\/\">JavaScript<\/a>, it&#8217;s important to handle any errors that may occur during the process. This is especially important if you&#8217;re working with a third-party API, as you have no control over the availability or consistency of the data that you&#8217;re requesting. With Axios, a popular library for making HTTP requests in JavaScript, you can handle errors by using the <code>catch<\/code> method of the promise returned by the <code>axios<\/code> method.<\/p>\n<p>Another way is to use try-catch block to handle errors. This will allow you to catch any errors that occur within the <code>try<\/code> block and handle them appropriately within the <code>catch<\/code> block.<\/p>\n<p>Alternatively, You can add global error handling by creating an instance of axios and attaching <code>interceptors.response.use<\/code> that allows you to handle all the errors at one place.<\/p>\n<p>Here&#8217;s an example of how you might use the <code>catch<\/code> method to handle errors when making a GET request:<\/p>\n<pre lang=\"javascript\" escaped=\"true\">axios.get('https:\/\/www.example.com')\r\n  .then(response =&gt; {\r\n    \/\/ do something with the data\r\n  })\r\n  .catch(error =&gt; {\r\n    if (error.response) {\r\n      \/\/ The request was made and the server responded with a status code\r\n      \/\/ that falls out of the range of 2xx\r\n      console.log(error.response.data);\r\n      console.log(error.response.status);\r\n      console.log(error.response.headers);\r\n    } else if (error.request) {\r\n      \/\/ The request was made but no response was received\r\n      \/\/ `error.request` is an instance of XMLHttpRequest in the browser and an instance of\r\n      \/\/ http.ClientRequest in node.js\r\n      console.log(error.request);\r\n    } else {\r\n      \/\/ Something happened in setting up the request that triggered an Error\r\n      console.log('Error', error.message);\r\n    }\r\n    console.log(error.config);\r\n  });\r\n\r\n<\/pre>\n<p>You can also use try-catch block<\/p>\n<pre lang=\"javascript\" escaped=\"true\">try {\r\n  const response = await axios.get('https:\/\/example.com');\r\n  \/\/ do something with response\r\n} catch (error) {\r\n   \/\/ handle error\r\n}\r\n\r\n<\/pre>\n<p>You can also add global error handling by creating an instance of axios and attaching <code>interceptors.response.use<\/code><\/p>\n<pre lang=\"javascript\" escaped=\"true\">const instance = axios.create();\r\ninstance.interceptors.response.use(response =&gt; {\r\n  \/\/ Do something with response data\r\n  return response;\r\n}, error =&gt; {\r\n  \/\/ Handle errors\r\n  return Promise.reject(error);\r\n});\r\n\r\n<\/pre>\n<p>It is essential to handle the errors efficiently and <a href=\"https:\/\/www.ardorsys.com\/ui-ux-design-services\/\">provide a better user experience<\/a> and also it is a good practice to prevent bugs in your <a href=\"https:\/\/www.ardorsys.com\/mobile-apps-development\/\">application<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"There are several ways to make HTTP requests in JavaScript, but the most common way is to use the XMLHttpRequest object, which is built into most web browsers.\n","protected":false},"author":1,"featured_media":6970,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[150,60,44],"tags":[151,61],"class_list":{"0":"post-6965","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-javascript","8":"category-nodejs","9":"category-web-development","10":"tag-javascript","11":"tag-nodejs"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6965","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/comments?post=6965"}],"version-history":[{"count":4,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6965\/revisions"}],"predecessor-version":[{"id":6973,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6965\/revisions\/6973"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media\/6970"}],"wp:attachment":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media?parent=6965"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/categories?post=6965"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/tags?post=6965"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}