javascript - Express.js 显示未定义的 req.body,其中路由从其他文件重新组合
问题描述
我是使用 Node.js Express 框架的初学者。我遵循了 Express 框架中的教程和试验路线。我正在尝试为 API 调用做准备并重新组合我的路线。我在 index.js 中有这样的结构
const express = require('express');
const http = require('http');
const dishRouter = require('./routes/dishRouter');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use('/dishes', dishRouter);
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
});
我正在从不同的文件中重新组合我的路线,并且在接受req.body.name
和req.body.description
在 disRouter.js 下面的代码中遇到问题:
const express = require('express');
const dishRouter = express.Router();
const bodyParser = require('body-parser');
dishRouter.route('/')
.all((req,res,next) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
next();
})
.get((req,res,next) => {
res.end('Will send all the dishes to you!');
})
.post((req, res, next) => {
res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description);
})
.put((req, res, next) => {
res.statusCode = 403;
res.end('PUT operation not supported on /dishes');
})
.delete((req, res, next) => {
res.end('Deleting all dishes');
});
dishRouter.use(bodyParser.json());
dishRouter.route('/:dishId')
.get((req, res, next) => {
res.end('Will send the dish id: ' + req.params.dishId + ' to you!');
})
.put((req, res, next) => {
res.write('Updating the dish: ' + req.params.dishId + '\n');
res.end('Will update the dish: ' + req.body.name +
' with details: ' + req.body.description);
});
module.exports = dishRouter;
在这里,我已经分开了我的路线,但是当我在 Postman 中尝试时req.body.name
,req.body.description
它给了我未定义的值。
我怎样才能从中获得价值?
解决方案
你能不能尝试把中间件dishRouter.use(bodyParser.json());
先dishRouter.route('/')
运行然后只去路由。
更新
签出此沙箱
您可以尝试使用curl
来测试端点:
curl --location --request POST 'http://localhost:3000/dishes' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "new dish",
"description": "new dish description"
}'
或者使用 Postman 在您的本地环境中尝试。
希望它有所帮助:D