Trusted answers to developer questions

What is Access-Control-Allow-Origin in Axios?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

What is the origin?

The origin is the name of a hostscheme, hostname, and port, e.g., https://educative.io, or a file open at the localhost. It is where a web page originates from. When you open your web browser and go to https://educative.io, the origin of the web page displayed to you is https://educative.io or localhost:3000 (if you open a web app on your computer).

Issue with CORS

According to the CORS policy, images and objects can only be fetched from the same server from where the origin lies. It will make calls to the same origin.

However, if a Javascript is connected to access resources from a different server, you will get the No Access-Control-Header-Present error.

Solution

1. Modify the header

In your get request, add the following to the header in the app.get function:

res.header("Access-Control-Allow-Origin", "true");

You will also need to add the following to the response:

crossorigin:true

2. Installing CORS

You can add the following code to your code to solve the issue:

const cors = require('cors');
app.use(cors());

You will, however, have to install CORS on your machine before you can use this. You can install it by running:

npm i cors

3. Using Express

You can use CORS with express to resolve the issue as well. Add the following to your code:

const express = require('express')
const app = express()
app.use(cors())

RELATED TAGS

axios

CONTRIBUTOR

Fahad Farid
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?