Node Express无法接收React前端POST请求体问题求助
问题修复方案
1. React表单输入值绑定错误
你的input组件中,value属性错误绑定了this.state.value,但组件state定义的字段是name,这会导致输入框无法同步用户输入内容,提交的state值也不符合预期。
修复:
将input的value属性改为this.state.name:
<input type="text" value={this.state.name} name="name" onChange={this.handleChange} />
2. Fetch请求未正确配置请求头与请求体
当前你直接传递固定字符串作为请求体,且未设置Content-Type请求头,而服务器端使用express.json()中间件解析JSON格式的请求体,这会导致服务器无法识别请求体格式,最终解析出空的req.body。同时你需要提交的是用户输入的name值,而非固定字符串。
修复:
- 添加
Content-Type: application/json请求头 - 将state中的name值转为JSON字符串作为请求体:
fetch('http://localhost:6969/Communication', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(this.state), }).then(res => res.json()) .then(data => console.log('服务器响应:', data)) .catch(err => console.error('请求错误:', err));
3. 处理跨域问题(必要补充)
React应用与Express服务器运行在不同端口,属于跨域请求,即使当前连接看似正常,后续可能出现请求被浏览器拦截的情况,建议添加CORS中间件。
安装cors依赖:
npm install cors
在服务器中引入并使用:
const cors = require('cors'); onlineStoreServer.use(cors()); // 需放在express.json()之前
修正后的完整代码
MyForm.js
import React from 'react' class MyForm extends React.Component { constructor(props) { super(props); this.state = { name: '' }; } handleChange = (event) => { this.setState({[event.target.name]: event.target.value}); } handleSubmit = (event) => { alert('表单已提交: ' + JSON.stringify(this.state)); fetch('http://localhost:6969/Communication', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(this.state), }).then(res => res.json()) .then(data => console.log('服务器响应:', data)) .catch(err => console.error('请求错误:', err)); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.name} name="name" onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } export default MyForm;
onlineStoreServer.js
const express = require('express'); const cors = require('cors'); const onlineStoreServer = express(); onlineStoreServer.use(cors()); onlineStoreServer.use(express.json()); onlineStoreServer.post("/Communication", async(req, res) => { console.log("收到POST请求!"); console.log("请求体内容:", req.body); // 返回响应避免请求挂起 res.status(200).json({ success: true, receivedName: req.body.name }); }) onlineStoreServer.listen(6969, () => { console.log("监听端口6969 B)"); });
内容的提问来源于stack exchange,提问作者Nessbound
相关产品推荐
相关产品推荐

