Search code examples
node.jscors

Why does the Cors does not work in NodeJS


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


Solution

  • 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);