Home > front end >  CORS header 'Access-Control-Allow-Origin'
CORS header 'Access-Control-Allow-Origin'

Time:11-08

What's the wrong in my code?

I used 'cors' package to pass cors policy, but it doesn't work.

My server code is:

const express = require("express");
const app = express();
require("dotenv").config();

const bodyParser = require("body-parser");
const cors = require("cors");
const { routes } = require("./routes/auth.routes");
const stripe = require("./routes/stripe");
const ObjectId = require("mongodb").ObjectId;

require('./db/db')();
app.use("/auth", routes)

const port = 5000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

Cors error

CodePudding user response:

I usually fix this error by adding a proxy to my frontend. In the package.json of your frontend add:

 "proxy": "http://localhost:5000"

And then while requesting to the backend, use something like this

const res = await axios.get("/auth/Login");

Since you used a proxy, you don't need to keep using "http://localhost:5000" again.

CodePudding user response:

Add the "Routes" middleware after initializing you server with "cors" middleware.

const express = require("express");
const app = express();
require("dotenv").config();

const bodyParser = require("body-parser");
const cors = require("cors");
const { routes } = require("./routes/auth.routes");
const stripe = require("./routes/stripe");
const ObjectId = require("mongodb").ObjectId;

require('./db/db')();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

app.use("/auth", routes)

const port = 5000;

Applying the cors middleware afterward prevents your middleware from setting the cors headers before to reaching the endpoint. Because of this, you must first configure the Cors middleware and then attach all of your routes to the server.

  • Related