Search code examples
node.jsangularexpresscors

Nodejs Express api cors error on calling api using angular frontend


I created api using nodejs express mongodb and its giving cors error when i call api from angular application. I deployed this api on render then its working but gives an error on local.

Error

Access to XMLHttpRequest at 'localhost:3000/api/auth/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, isolated-app, brave, https, chrome-untrusted, data, chrome-extension, chrome. auth.service.ts:38 POST localhost:3000/api/auth/login net::ERR_FAILED schedu

I have installed cors and added app.use(cors({origin : "*"}))

or

app.use(cors({origin : "http://localhost:4200/"}))

But it still giving error.

Also, I tried adding this

    app.use((req, res, next) => {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT");
        res.setHeader("Access-Control-Allow-Headers", "Content-Type");
        next();
    }

still cors error.

here is my index.js

    const express = require("express");
    const app = express();
    const dotEnv = require("dotenv");
    const mongoose = require("mongoose");
    const cors = require("cors");

    app.use(cors({origin: "*"}));

    app.use((req, res, next) => {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT");
        res.setHeader("Access-Control-Allow-Headers", "Content-Type");
        next();
    }


    dotEnv.config();

    mongoose.set("strictQuery", false);
    app.use(express.json());

    mongoose.connect(process.env.DB_URL).then(function(){
        console.log("connected");

    });

    


    applications = require("./routes/applications"),
    auth = require("./routes/auth"),


    



    app.use("/api/aplications", applications);
    app.use("/api/auth/", auth);





    const PORT = process.env.PORT || 3000;

    app.listen(PORT, function(){
        console.log(Date.now())
        console.log("server started on port", PORT);
    })

Solution

  • i found solution i forgot to add http:// , its working now

    this.http.post('http://localhost:3000/api/auth/login',  { email: email, password:password })
      .subscribe((data:any) => {
        // console.log();
        this.setToken(data.token)
        console.log(data);
      });