如何在本地单端口实现NodeJS/Express后端与VueJS前端连通?
开发环境单端口访问实现方案
核心使用Vue CLI内置的devServer代理能力实现请求转发,无需额外引入nginx等反向代理工具即可满足需求,配置步骤如下:
- 根目录新建/修改
vue.config.js文件,添加代理规则:
module.exports = { devServer: { port: 8080, proxy: { '/api': { target: 'http://localhost:3000', // 替换为你的Express服务实际运行端口 changeOrigin: true, // 若后端接口无/api前缀,可添加下方配置去掉转发时的/api前缀 // pathRewrite: { '^/api': '' } } } } }
- Express开发环境开启跨域支持:
安装cors依赖:npm install cors
在后端入口文件添加配置:
const cors = require('cors') // 仅开发环境开启cors if (process.env.NODE_ENV === 'development') { app.use(cors()) }
注意:生产/Staging模式下前后端共用端口,不会产生跨域问题,无需开启cors,避免安全风险
三种运行模式配置参考
1. 开发模式
- 全局安装pm2实现后端服务后台运行:
npm install pm2 -g - 在
package.json中配置启动脚本:
"scripts": { "serve": "vue-cli-service serve", "start:be": "node ./app.js", // 替换为实际的后端启动入口路径 "dev": "pm2 start npm --name \"express-api\" -- run start:be && npm run serve" }
- 执行
npm run dev即可同时启动前后端服务,后端运行在后台不会阻塞终端,访问localhost:8080即可打开前端页面,所有/api前缀的请求会自动转发到Express服务。
2. Staging模式
- 安装cross-env实现跨平台环境变量设置:
npm install cross-env -D - 在
package.json中配置脚本:
"scripts": { "build:staging": "vue-cli-service build --dest ./dist", // 将打包产物输出到后端根目录的dist文件夹 "start:staging": "cross-env NODE_ENV=staging node ./app.js" }
- 后端入口文件添加静态资源服务逻辑:
const path = require('path') if (process.env.NODE_ENV !== 'development') { // 提供静态资源访问 app.use(express.static(path.join(__dirname, 'dist'))) // 适配Vue history路由,非API请求返回前端入口文件 app.get('*', (req, res) => { if (!req.path.startsWith('/api')) { res.sendFile(path.join(__dirname, 'dist', 'index.html')) } }) }
- 执行
npm run build:staging && npm run start:staging即可启动Staging服务,前后端共用同一端口。
3. 生产模式
- 在
package.json中配置脚本:
"scripts": { "build": "vue-cli-service build --dest ./dist", "start": "cross-env NODE_ENV=production node ./app.js" }
- 将包含dist打包产物的后端代码整体推送到Heroku即可,平台会自动执行构建命令并启动服务,实现前后端共用端口。
内容的提问来源于stack exchange,提问作者Coen
相关产品推荐
相关产品推荐

