[英]Express.js displaying the req.body undefined with routes regroup from other file
I am a beginner in using Node.js Express framework.我是使用 Node.js Express 框架的初学者。 I followed a tutorial and experimenting routes from Express framework.
我遵循了 Express 框架中的教程和实验路线。 I am trying to prepare for API call and regroup my routes.
我正在尝试为 API 呼叫做准备并重新组合我的路线。 I have a structure like this in index.js
我在 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}`);
});
I was regrouping my routes from a different file and I have a problem regarding on accepting req.body.name
and req.body.description
in the code below dishRouter.js:我正在从一个不同的文件重新组合我的路线,我在接受
req.body.name
和req.body.description
时遇到问题:
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;
Here I have separated my routes but when I tried in Postman, req.body.name
and the req.body.description
, it gives me undefined value.在这里,我已经分开了我的路线,但是当我在 Postman、
req.body.name
和req.body.description
中尝试时,它给了我未定义的值。
How can i get the values from this?我怎样才能从中获得价值?
Can you try to put dishRouter.use(bodyParser.json());
你能试试把
dishRouter.use(bodyParser.json());
before dishRouter.route('/')
so the middleware runs first then only go to the route.在
dishRouter.route('/')
之前,中间件首先运行,然后仅 go 到路由。
UPDATE更新
You can try by using curl
to test the endpoint:您可以尝试使用
curl
来测试端点:
curl --location --request POST 'http://localhost:3000/dishes' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "new dish",
"description": "new dish description"
}'
Or try in your local environment using Postman.或者在您的本地环境中尝试使用 Postman。
Hope it helps:D希望对你有帮助:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.