You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CORS中间件后仍出现MEAN Stack CORS错误,求解决方案

解决Angular+Node.js应用的CORS错误问题

问题描述

开发基于Angular前端+Node.js后端的应用时,即便已使用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
});

浏览器错误信息

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配置错误,而是前端请求URL缺少协议头:

  • 修正前端请求地址:将请求目标localhost:8088/login修改为http://localhost:8088/login。浏览器对跨域请求要求必须携带标准协议(http/https),不带协议的地址会被判定为非合规协议,直接触发CORS拦截。
  • 优化后端CORS配置(可选):当前配置中重复添加了localhost:4200,可简化为:
    let corsOptions = {
        origin: 'http://localhost:4200'
    }
    
    若后续需支持多个域名,再使用数组形式,确保每个域名都包含完整协议头。

内容的提问来源于stack exchange,提问作者mavilla vishnu vardhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:22:13