Express应用POST请求异常:curl与fetch表现不一致问题排查
问题原因与解决方案
问题根源
你在fetch请求中设置了mode: "no-cors",这是导致请求体无法被Express正确解析的核心原因。
当浏览器使用no-cors模式发送请求时,会强制执行跨域请求的限制规则:
- 你手动设置的
Content-Type: application/json会被浏览器忽略,实际发送的请求Content-Type会被替换为浏览器允许的"简单类型"(比如text/plain) - Express的
express.json()中间件只会解析Content-Type为application/json的请求体,因此无法识别这种被修改后的请求,最终req.body为空对象{}
而curl命令不受浏览器跨域规则限制,能正确发送Content-Type: application/json的请求,所以Express可以正常解析请求体。
解决方案
由于你的index.html是通过Express的express.static("./")托管在http://localhost:3333下的,请求同域名的/builtins接口不存在跨域问题,直接移除mode: "no-cors"即可:
修改后的index.html脚本部分:
<script> fetch("http://localhost:3333/builtins", { body: JSON.stringify(["wojtyla", "ratzinger", "madre teresa"]), headers: { "Content-Type": "application/json", }, method: "POST", }) .then((t) => t.text()) .then((t) => document.write(`<h1>Got response ${t}</h1>`)); </script>
验证
重启Express服务器后,在浏览器打开http://localhost:3333/index.html,此时Express日志会输出预期结果:
debug request body builtins [ 'wojtyla', 'ratzinger', 'madre teresa' ]
跨域场景扩展说明
如果你的页面和API不在同一域名下,不要使用mode: "no-cors",而是在Express端配置CORS中间件:
- 安装cors包:
npm install cors - 在Express应用中引入并使用:
import express from "express"; import cors from "cors"; const app = express(); app.use(cors()); // 允许所有跨域请求,可根据需求配置参数 app.use(express.json()); // ... 其他代码
内容的提问来源于stack exchange,提问作者pedroth
相关产品推荐
相关产品推荐

