Vercel部署前后端独立正常,前端无法加载后端数据求助
问题:Vercel部署后前端无法加载后端数据,报错
ERR_CONNECTION_REFUSED 问题描述
今日将前后端部署至Vercel平台,此前后端出现非404错误,按建议将根文件从server.js改为index.js后后端恢复正常。目前前后端均已部署且独立运行正常,但前端加载后端数据时报错Failed to load resource: net::ERR_CONNECTION_REFUSED。本地运行时前后端功能正常,本地启动后端时,已部署的前端也能正常工作。
已部署后端状态截图

前端报错截图

相关代码
后端index.js代码
// 导入所需模块 const express = require('express'); require('dotenv').config(); const mongoose = require('mongoose'); const cors = require('cors') const NoteRoutes = require('./routes/noteRoutes') const { getCategory, deleteCategory, getOneCategryData } = require('./controller/categoryController') const { getDynamicNoteData, DeleteInActiveNotes, AutoHardDeleteNotes } = require('./controller/noteController') // 初始化express应用 const app = express(); // 解析JSON请求的中间件 app.use(express.json()) // 处理CORS策略的中间件 app.use(cors()); app.get('/', (req, res) => { res.json({ message: '欢迎来到笔记API' }) }) app.use('/note', NoteRoutes) // 因类型转换问题手动创建路由 app.get('/search', getDynamicNoteData) app.delete('/remove', DeleteInActiveNotes) app.get('/category', getCategory) app.get('/category/:id', getOneCategryData) app.delete('/category/:id', deleteCategory) const PORT = process.env.PORT; const URL = process.env.URL; // 使用mongoose连接MongoDB数据库 mongoose.connect(URL) // 连接成功时输出信息 .then(() => { console.log("已连接MongoDB"); // 调用自动删除函数 AutoHardDeleteNotes() // 启动服务监听端口 app.listen(PORT, () => { console.log("服务器运行在端口 " + PORT); }) }) // 连接失败时输出错误信息 .catch(err => { console.log("应用出现以下错误:\n" + err); })
前端相关代码
const fetchDefaultNotes=()=>{ setLoading(true) axios.get('http://localhost:3000/note/active') .then((res)=>{ setNotes(res.data.data); setLoading(false) console.log(res.data) }) .catch((err)=> console.log(err) ) }
解决方案
核心问题
前端代码硬编码了本地后端地址http://localhost:3000,部署到Vercel后,线上环境不存在本地3000端口服务,因此触发连接拒绝错误。
具体修复步骤
替换硬编码的API地址
将前端请求中的http://localhost:3000替换为Vercel上部署的后端实际域名,例如:axios.get('https://your-backend-vercel-domain.vercel.app/note/active')推荐:用环境变量管理API地址
避免本地/线上环境切换时手动修改地址:- 本地开发:在前端项目的
.env文件中添加REACT_APP_API_URL=http://localhost:3000(React项目示例,其他框架对应调整); - 线上部署:在Vercel前端项目设置中添加环境变量
REACT_APP_API_URL,值为后端线上域名; - 前端代码中使用环境变量:
axios.get(`${process.env.REACT_APP_API_URL}/note/active`)
- 本地开发:在前端项目的
优化CORS配置(可选)
若前端与后端域名不同,可更精确配置CORS策略,避免潜在跨域问题:app.use(cors({ origin: process.env.FRONTEND_URL, // 例:https://your-frontend-vercel-domain.vercel.app credentials: true }));同时在Vercel后端项目的环境变量中设置
FRONTEND_URL为前端线上地址。
内容的提问来源于stack exchange,提问作者nawola
相关产品推荐
相关产品推荐

