名为 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!
,我无法解决问题。
对于其他方法调用,我也需要相同的响应。