1

I'm enduring a CORS problem in NodeJS and the front end of Vue.js. The problem is

Access to XMLHttpRequest at 'http://localhost:3007/auth/login' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Help me out with the problem

Let me share my code what i have tried.

import express from "express";
import mongoose from "mongoose";
import { config } from "dotenv";
import { router as loginRoute } from "./routes/login.js";
import cors from "cors";
import "dotenv/config.js";

const app = express();
app.use(express.json());

// Server connect
app.listen(3007, () => {
    console.log(`I m listening on 3007`);
});

// route
app.use("/auth", loginRoute);

// CORS Cross Orgin Resource Sharing

app.use(
 cors({
     origin: "http://localhost:5173",
     optionsSuccessStatus: 200,
     methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
     preflightContinue:false
 })
);

and i have tried this code too app.use(cors()); still it doesn't work

Hiro Doublin
  • 1
  • 2
  • 13
  • 1
    you need to add OPTIONS to the array of allowed methods – Dev Man Aug 31 '23 at 08:11
  • Which browser do you use? Very often this error is comming from browser. – Borislav Stefanov Aug 31 '23 at 08:14
  • This might help you: [Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?](https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my) – Ingo Steinke Aug 31 '23 at 08:17
  • 1
    @DevMan No, you only need to list `OPTIONS` as an allowed method if the client uses `OPTIONS` as the method of his _actual_ request. That is a common misunderstanding about CORS, though. – jub0bs Aug 31 '23 at 08:22

1 Answers1

4

Make sure to place the CORS middleware before defining your routes to ensure that it's applied to all routes. With this configuration, the required Access-Control-Allow-Origin header will be included in responses from your server, allowing your Vue.js frontend to access the resources.

You can do this:

import express from "express";
import cors from "cors";
import { router as loginRoute } from "./routes/login.js";

const app = express();
app.use(express.json());

// CORS configuration
app.use(
 cors({
     origin: "http://localhost:5173",
     optionsSuccessStatus: 200,
     methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
     preflightContinue: false
 })
);

// Server connect
app.listen(3007, () => {
    console.log(`I'm listening on 3007`);
});

// route
app.use("/auth", loginRoute);
Hittapa Co
  • 56
  • 3