NodeJS MEAN堆栈CORS错误,即使在使用CORS中间件之后

0pizxfdo  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我正在使用NodeJs后端开发一个Angular应用程序,即使在使用CORS中间件之后,我也会收到CORS错误。看看我的代码:

var mysql = require('mysql');
const fs = require('fs');
const express = require('express');
const app = express();
const cors = require('cors');
let corsOptions = {
    origin: ['http://localhost:4200', 'localhost:4200'],
}
app.use(cors(corsOptions));

var bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const saltRounds = 10;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.post('/login', (req, res) => {
//Code
});

字符串
以下是Chrome上的错误:

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

POST localhost:8088/login net::ERR_FAILED


我如何解决这个CORS错误现在让我现在请!

owfi6suc

owfi6suc1#

您提供的代码在corsOptions对象中指定的源URL有问题。源应该包括方案(例如,“http://”),但它们缺少它。要修复CORS错误,请像这样更新corsOptions对象:

let corsOptions = {
    origin: ['http://localhost:4200'],
}

字符串
此更改确保CORS中间件正确工作,允许您的Angular应用程序与Node.js后端通信而不会遇到CORS错误。

相关问题