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

ExpressJS跨域配置无效,Angular请求报Access-Control错误求助

CORS Error with Express Server: No 'Access-Control-Allow-Origin' header despite configuration

嘿,我一眼就发现问题出在哪了!你的CORS中间件被放在了路由挂载之后,这就导致/api/todos的请求根本没经过CORS头的处理,自然会报错。

先再明确下你遇到的错误:

Failed to load http://localhost:3000/api/todos: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Express的中间件是按代码顺序执行的,你先挂载了/api/todos路由,之后才设置CORS响应头的中间件——这意味着当请求匹配到/api/todos时,路由处理会直接返回响应,后面的CORS中间件根本没机会运行,所以响应里不会带上那些允许跨域的头。

解决方案:调整中间件顺序

把你的CORS相关中间件(不管是手动写的还是cors())移到所有路由挂载之前,这样所有请求都会先经过CORS处理。

修改后的app.js代码:

const app = express(); 
// view engine setup 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'ejs'); 
// uncomment after placing your favicon in /public 
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); 
app.use(logger('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: false})); 
app.use(cookieParser()); 
app.use(express.static(path.join(__dirname, 'public'))); 

// 先加载CORS中间件!
app.use(function(req, res, next) { 
  res.header("Access-Control-Allow-Origin", '*'); 
  res.header("Access-Control-Allow-Credentials", true); 
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); 
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'); 
  next(); 
}); 

// 再挂载路由
app.use('/api/todos', require('./routes/todos.route').todos); 

mongoose.Promise = bluebird; 
mongoose.connect('mongodb://127.0.0.1:27017/mean-app2') 
.then(() => { 
  console.log(`Succesfully Connected to the Mongodb Database at URL : mongodb://127.0.0.1:27017/mean-app2`) 
}) 
.catch(() => { 
  console.log(`Error Connecting to the Mongodb Database at URL : mongodb://127.0.0.1:27017/mean-app2`) 
}); 
module.exports = app; 

更简洁的方案:使用cors包

如果你用cors包的话,它会自动处理OPTIONS预检请求,比手动写中间件更可靠,同样要确保它在路由之前加载:

const cors = require('cors');

// ... 其他初始化代码
app.use(cors({
  origin: '*',
  credentials: true,
  methods: ['GET','PUT','POST','DELETE','OPTIONS'],
  allowedHeaders: ['Origin','X-Requested-With','Content-Type','Accept','content-type','application/json']
}));

// 之后再挂载路由
app.use('/api/todos', require('./routes/todos.route').todos);

调整完顺序后重启服务器,应该就能解决这个CORS问题了!

内容的提问来源于stack exchange,提问作者Kiwi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:38:52