javascript - 为什么我在使用 NODEJS 和 EXPRESSJS 通过 RESTAPI 中的参数(ID)向服务器发出请求后没有收到正确的响应
问题描述
名为 Node 的模块dishRouter.js
实现了/dishes/:dishId
REST API 端点的 Express 路由器。
index.js
const express = require('express');
const http = require('http');
const morgan = require('morgan');
const hostname = 'localhost';
const port = 3000;
const app = express();
const dishRouter = require('./routes/dishRouter');
const bodyParser = require('body-parser');
app.use(morgan('dev'));
app.use(bodyParser.json()); //parse the json in the body
app.use('/dishes/:dishId', dishRouter);
app.use(express.static(__dirname + '/public'));
app.use((req, res, next) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is an express server</h1></body></html');
});
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`)
});
菜路由器.js
const express = require('express');
const bodyParser = require('body-parser');
const dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.all((req, res, next) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
next();
})
.get((req, res, next) => {
res.end('Will send details of the dish: ' + req.params.dishId + ' to you!');
})
.post((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);
})
.put((req, res, next) => {
res.end(req.params.dishId + ' Will update the dishId and dish: ' + req.body.name + 'with details: ' + req.body.description);
})
.delete((req, res, next) => {
res.end('Deleting the dishId: ' + req.params.dishId);
});
module.exports = dishRouter;
向 发送GET
请求时localhost:3000/dishes/28
,将发送以下响应:
Will send details of the dish: undefined to you!
但我需要的是Will send details of the dish:28 to you!
,我无法解决问题。
对于其他方法调用,我也需要相同的响应。
解决方案
当您将路由器存储在 中时dishRouter
,您需要告诉它从父母那里继承参数。
...
const dishRouter = express.Router({ mergeParams: true });
...
推荐阅读
- office365 - Sharepoint Online - 创建页脚
- c# - Unity 5.5.6f1 - 本机插件不起作用,错误 DllNotFoundException
- angular - 在 .html 文件中而不是在 .ts 文件中以 Angular 4 编写最大代码会更好吗?
- python - OSError:[Errno 30] Heroku 上 Django 中的只读文件系统
- omnet++ - 仅使用 SUMO 与同时使用 SUMO、Veins 和 OMNeT++ 的不同输出
- ajax - 带缓存的无限/分页滚动
- mysql - 加入多个唯一键表,但只返回一行
- httpclient - 从 HTTP 响应中提取数据 - Angular 5
- xamarin.ios - 如何将 IReadonlyReactiveList 绑定到 ReactiveCollectionView
- javascript - NodeJS Express - 返回它触发的 URL 路径的 JSON 文件