【发布时间】:2020-12-01 10:20:05
【问题描述】:
我是服务器端开发的新手。
我正在尝试设置一个可以接收帖子的 node.js 服务器。
我的客户端-服务器代码发送 post 请求:
function post(){
fetch('/clicked', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Text'})
})
.then(function(response){
if(response.ok){
console.log('POST success.');
return;
}
throw new Error('POST failed.');
})
.catch(function(error){
console.log(error);
});
}
我的 Node.js 服务器接收到它:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
})
但是,我的服务器控制台记录了所有 undefined。
我应该怎么做才能收到我的 POST 请求正文?
【问题讨论】:
-
你是否在你的 nodejs 中使用了任何类型的
body-parser- 看起来不像 - 类似于app.use(express.json())
标签: javascript node.js http post