Express后端正常响应Postman请求,前端fetch发POST请求body为null如何解决?
问题根源
你代码的核心错误是fetch请求配置了mode: 'no-cors':
no-cors是专门用于跨域请求静态资源的模式,该模式下浏览器会禁止设置Content-Type: application/json这类自定义请求头,也会限制请求体的正常传输,Express的express.json()中间件识别不到对应的请求头,就会将req.body解析为空。- 同时
no-cors模式下返回的响应是opaque不透明类型,前端无法读取响应的具体内容,所以你打印response.body会得到null。
修复步骤
- 删除前端JS代码中fetch配置里的
mode: 'no-cors'行。 - 给Express服务配置跨域支持,避免删掉no-cors后出现跨域报错:
- 先安装cors依赖:
npm install cors- 修改后端代码,引入并启用cors:
const express = require('express') const cors = require('cors') const app = express() app.use(cors()) // 放在其他中间件之前 app.use(express.static('public')) app.use(express.json()) app.listen(3000, () => console.log('listening at port 3000')) app.post('/api/', (req, res) => { console.log('A post request have recieved') console.log(req.body) res.send('This is the body of that POST request' + JSON.stringify(req.body)) }) - 修正前端响应解析逻辑,fetch返回的response对象不能直接读取body内容,需要调用
text()或json()方法解析:function buttonFunc() { const data = { name: 'john', } console.log('clicked') const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), } fetch('http://localhost:3000/api/', options) .then(function (response) { return response.text() // 后端返回字符串用text(),如果返回JSON格式就用response.json() }) .then(function (data) { console.log(data) }) .catch(function (error) { console.error(error) }) }
完成以上三步后即可正常发送请求、拿到后端返回的内容。
内容的提问来源于stack exchange,提问作者Shaheer.K
相关产品推荐
相关产品推荐

