Node.js Express API 在使用 Angular 前端调用 API 时出现 CORS 错误。

huangapple go评论130阅读模式
英文:

Nodejs Express api cors error on calling api using angular frontend

问题

I created API using Node.js Express MongoDB, and it's giving a CORS error when I call the API from an Angular application. I deployed this API on Render, and then it's working, but it gives an error locally.

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.

I have installed CORS and added:

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

or

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

But it still gives an 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, I'm getting a 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);
})

(Note: I've corrected some code formatting issues in your provided code.)

英文:

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

答案1

得分: 1

基于cors npm文档,我认为你需要像这样调用cors()并传递空参数:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
app.get('/products/:id', function (req, res, next) {
  res.json({msg: '这是允许所有来源的CORS!'})
})

app.listen(80, function () {
  console.log('CORS启用的Web服务器正在监听端口80')
})
英文:

based on cors npm documentation
i think you need to call cors() with empty parameter like this :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var express = require(&#39;express&#39;)
var cors = require(&#39;cors&#39;)
var app = express()
 
app.use(cors())
app.get(&#39;/products/:id&#39;, function (req, res, next) {
  res.json({msg: &#39;This is CORS-enabled for all origins!&#39;})
})
 
app.listen(80, function () {
  console.log(&#39;CORS-enabled web server listening on port 80&#39;)
})

<!-- end snippet -->

答案2

得分: 0

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

英文:

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

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

huangapple
  • 本文由 发表于 2023年5月7日 22:33:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定