简体   繁体   English

Express中的路线顺序重要吗?

[英]does the order of routes matter in Express?

im trying to build this simple CMS with Restfull routes in Express.js,我试图在 Express.js 中使用 Restfull 路由构建这个简单的 CMS,

it was working just fine.它工作得很好。 then i tried to change it a lil bit so that my routes get neater(or not).so i moved router.get('/new') route below router.post('/') route and it just stopped working as normal.然后我尝试稍微更改一下,以便我的路由变得更整洁(或不整洁)。所以我将router.get('/new')路由移到 router.post(' router.post('/') ') 路由下方,它只是停止正常工作. when i try to get /new route the request goes to router.get('/')当我尝试获取/new路由时,请求转到router.get('/')

this is the related part of my app.js (removed the unnessary parts)这是我的app.js的相关部分(删除了不必要的部分)

var express=require('express'),
blogRoutes =require('./routes/blogs.js'),
app        =express();

app.use('/blogs',blogRoutes);

and this is my blogs route in blogs.js file (removed unnessary parts)这是我在blogs.js文件中的博客路由(删除了不必要的部分)

var express = require('express'),
    router  = express.Router();


router.get('/',function(req,res){...});
router.get('/:id',function(req,res){...});

router.post('/',function(req,res){...});
router.get('/new',function(req,res){...});

router.get('/:id/edit',function(req,res){...});
router.put('/:id',function(req,res){...});
router.delete('/:id',function(req,res){...});

so i want to know how does this work cuz i did not find anything usefull about the order of routes other than the RESTfull routes images on net that new is before create routes.yet it does make any sense why it can't process it correctly.所以我想知道这是如何工作的,因为除了创建路由之前的网络上的 RESTfull 路由图像之外,我没有发现任何关于路由顺序的有用信息。但它确实有任何意义,为什么它不能正确处理它.

Try moving router.get('/',function(req,res){...});尝试移动router.get('/',function(req,res){...}); to the bottom of the list, that's the root router.到列表的底部,那是根路由器。

From Express docs:来自 Express 文档:

A route will match any path that follows its path immediately with a “/”.路由将匹配紧随其路径的任何路径,并带有“/”。

For example: app.use("/apple", ...) will match “/apple”, “/apple/images”,“/apple/images/news”,例如: app.use("/apple", ...) 将匹配“/apple”、“/apple/images”、“/apple/images/news”、

and so on.等等。

It is a healthy approach to move router.get('/',function(req,res){...});移动router.get('/',function(req,res){...});是一种健康的方法。 to the bottom.至底部。

If you move router.get('/:id',function(req,res){...});如果你移动router.get('/:id',function(req,res){...}); below router.get('/new',function(req,res){...});下面router.get('/new',function(req,res){...}); that should fix your problem.那应该可以解决您的问题。 It is good idea to put router.get('/:id' before router.get('/:id/edit' .router.get('/:id' router.get('/:id/edit'之前) 是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM