Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

axios

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

Fahad Farid

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring