首页 > 解决方案 > 为什么在请求特定参数后我没有得到正确的响应?(使用 NodeJS 和 Express 路由器的 REST API)

问题描述

使用 Express 路由器创建了一个节点模块,以支持菜肴 REST API 的路由。

索引.js 文件:

const express = require('express');
const http = require('http');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();  // here we are saying that our application are going to use express node module
const dishRouter = require('./route/dishRouter');
app.use('/dishes/:dishId', dishRouter);

const hostname = 'localhost';
const port = 3000;





app.use(bodyParser.json());  // This allows us to parse the body of the request message

app.use(morgan('dev')); //it will print out additional information to the screen as required

app.use(express.static(__dirname + '/public')); // This will serve the static files


app.use((req, res, next) => {
    console.log(req.headers);
    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); // here we set up the server using express App

server.listen(port,hostname,() => {
    console.log(`Server runnig at http://${hostname}:${port}`);
})

DishRouter.js 文件:

const express = require('express');
const bodyparser = require('body-parser');

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

dishRouter.use(bodyparser.json());

dishRouter.route('/') //mount this express router at the /dishes endpoint.chain all GET PUT POST DELET method already do this router

.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 is not supported by /dishes');
})
.delete((req,res,next) => {
    res.end('Deleting all the dishes');
});

// Routes for specific dish 
dishRouter.route('/:dishId')
.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send the dish ' +req.params.id +' to you!');
})
.post((req,res,next) => {
     res.statusCode = 403;
    res.end('POST operation not supported on /dishes/'+req.params.id);
})
.put((req,res,next) => {
    res.write('Updating the dish: ' + req.params.id + '\n');
    res.end("Will add the dish : " + req.body.name + " with details: " + req.body.description);
})
.delete((req,res,next) => {
    res.end('Deleting the dish '+req.params.id);
});

module.exports = dishRouter ;

这需要支持每个端点上的 GET、PUT、POST 和 DELETE 操作。该代码适用于菜肴,但对于 discId,它显示的结果与菜肴相同。

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

会把所有的菜都送给你!

标签: javascriptnode.jsrestexpressexpress-router

解决方案


快速路线以先到先得的方式匹配。因此,因为您的根路由/将匹配任何路由并且它是首先定义的,所以它将始终使用该路由。尝试将根路径移动到文件底部。IE

const express = require('express');
const bodyparser = require('body-parser');

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

dishRouter.use(bodyparser.json());

// Routes for specific dish 
dishRouter.route('/:dishId')
.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send the dish ' +req.params.id +' to you!');
})
.post((req,res,next) => {
     res.statusCode = 403;
    res.end('POST operation not supported on /dishes/'+req.params.id);
})
.put((req,res,next) => {
    res.write('Updating the dish: ' + req.params.id + '\n');
    res.end("Will add the dish : " + req.body.name + " with details: " + req.body.description);
})
.delete((req,res,next) => {
    res.end('Deleting the dish '+req.params.id);
});

dishRouter.route('/') //mount this express router at the /dishes endpoint.chain all GET PUT POST DELET method already do this router

.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 is not supported by /dishes');
})
.delete((req,res,next) => {
    res.end('Deleting all the dishes');
});
module.exports = dishRouter ;

推荐阅读