React FullCalendar组件事件存入数据库时POST请求出现net::ERR_FAILED网络错误求助
我帮你排查了这个POST请求失败的问题,主要有几个关键点需要修正,咱们一步步来解决:
1. Axios请求URL缺少协议头(最直接的触发原因)
你在React客户端的handleEventAdd和handleDateSet方法里,axios的URL写的是localhost:4000/...,浏览器会把这个当成相对路径或者无效的URL格式,导致请求无法正确发送到后端服务。
修正代码:
给URL加上http://前缀:
// handleEventAdd里的请求 axios.post("http://localhost:4000/events/create-event", data.event) // handleDateSet里的请求 const response = await axios.get("http://localhost:4000/events/get-events?start="+moment(data.start).toISOString()+"&end="+moment(data.end).toISOString())
2. 跨域资源共享(CORS)拦截问题
React开发服务器默认跑在localhost:3000,你的后端服务在localhost:4000,属于不同端口的跨域请求,浏览器会自动拦截这类请求,这也是导致ERR_FAILED的常见原因。
解决方法:
在Express后端安装并配置CORS中间件:
- 先安装cors包:
npm install cors
- 在你的主Express入口文件(比如
app.js)里添加配置:
const cors = require('cors'); app.use(cors()); // 开发环境允许所有跨域请求,生产环境可以配置更严格的域名规则
3. 后端创建事件的数据结构错误
看你的后端路由代码,创建事件时你把请求体的event包在了events字段里:
const events = { events:req.body.event } const newEvent = new Events(events)
但你的Mongoose模型EventSchema定义的字段是start、end、title,并没有events字段,这样存到数据库的文档结构完全不符合模型要求,甚至会导致保存失败。
修正代码:
直接使用req.body.event作为新事件的参数:
router.route('/create-event').post((req, res) => { const newEvent = new Events(req.body.event) newEvent.save() .then(() => res.json(newEvent)) .catch(err => res.status(400).json('Error: ' + err)) })
4. 确认后端路由的挂载路径
要确保你的主Express文件(app.js)里正确挂载了事件路由到/events路径,比如:
const eventRouter = require('./routes/your-event-router-file'); // 替换成你的路由文件实际路径 app.use('/events', eventRouter);
如果挂载路径不对,请求/events/create-event会返回404,同样会触发ERR_FAILED错误。
额外建议:添加请求错误捕获
在React客户端的axios请求里加上错误捕获,方便后续排查问题:
const handleEventAdd = (data) => { console.log(data.event) axios.post("http://localhost:4000/events/create-event", data.event) .then(response => console.log("Event saved successfully:", response.data)) .catch(err => console.error("Failed to save event:", err)) }
内容的提问来源于stack exchange,提问作者Chen
相关产品推荐
相关产品推荐

