javascript - 为什么我在使用 NODEJS 和 EXPRESSJS 通过 RESTAPI 中的参数(ID)向服务器发出请求后没有收到正确的响应

标签 javascript node.js rest express server-response

名为 dishRouter.js 的 Node 模块为 /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}`)
});

dishRouter.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;

localhost:3000/dishes/28 发送 GET 请求时,会发送以下响应:

Will send details of the dish: undefined to you!

但我需要的是将菜品的详细信息:28发送给你!,而我无法解决这个问题。

我还需要对其他方法调用做出相同的响应。

最佳答案

当您将 Router 存储在 dishRouter 中时,您需要告诉它从父级继承参数。

...
const dishRouter = express.Router({ mergeParams: true });
...

Express document

关于javascript - 为什么我在使用 NODEJS 和 EXPRESSJS 通过 RESTAPI 中的参数(ID)向服务器发出请求后没有收到正确的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334228/

相关文章:

javascript - react 导航 : Component is not being unmounted on pop or back button #5775

javascript - 如何通过node.js获取电报机器人用户注册日期?

javascript - Ember-Data 并将数据拉入存储

javascript - 更改函数内的原型(prototype)

delphi - Indy 和 REST - 我可以防止异常吗?

c# - 从 Silverlight 调用 REST 服务

javascript - 对象声明 : Do strings as keys make a difference?

Javascript 重定向或重新加载

javascript - 为什么我们应该使用 $().each 方法?

javascript - ReactJS 服务器端渲染与热重载 (webpack-dev-server)