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

如何让Express的server.js允许Angular 6跨域请求?

解决Angular 6与Express服务的跨域请求问题

你遇到的是典型的**跨域资源共享(CORS)**问题——因为Angular运行在4200端口,而Express服务在3000端口,浏览器的同源策略会阻止这种跨端口的请求,除非服务端明确允许来源访问。

下面是两种简单有效的修改方式,任选其一即可:

方式一:手动添加CORS响应头

直接在Express应用中添加自定义中间件,设置允许的来源和请求规则:

修改你的server.js,在引入依赖之后、设置静态路径之前,插入这段中间件代码:

// 手动配置CORS规则
app.use((req, res, next) => {
  // 允许Angular所在的4200端口发起请求
  res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
  // 允许携带的请求头类型
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // 允许的HTTP请求方法
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  // 处理浏览器发送的OPTIONS预检请求
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

修改后的完整server.js代码如下:

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
const app = express();

// 手动配置CORS规则
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
 res.sendFile(path.join(__dirname, 'dist/myproject/index.html'));
});
/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);
/**
 * Create HTTP server.
 */
const server = http.createServer(app);
/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

方式二:使用cors npm包(更推荐)

如果你的项目后续需要更灵活的CORS配置(比如允许多个来源、自定义规则),使用官方维护的cors包会更省心:

  1. 先安装依赖包:
npm install cors --save
  1. 在server.js中引入并使用:
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors'); // 引入cors包
// Get our API routes
const api = require('./server/routes/api');
const app = express();

// 配置CORS,仅允许4200端口的请求
app.use(cors({ origin: 'http://localhost:4200' }));

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
 res.sendFile(path.join(__dirname, 'dist/myproject/index.html'));
});
/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);
/**
 * Create HTTP server.
 */
const server = http.createServer(app);
/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

额外提示

  • 生产环境中不要用*允许所有来源,一定要指定具体的业务域名/端口,避免安全风险。
  • 浏览器会对PUT、DELETE这类复杂请求先发送OPTIONS预检请求,手动配置时必须处理这种请求(方式一中的if (req.method === 'OPTIONS')就是做这件事的)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:24:49