簡體   English   中英

Express.js 4 路由與 router.route 不匹配

[英]Express.js 4 routes not matching with router.route

我正在嘗試掌握 Express 4 中 router.route 的竅門。文檔使它聽起來很棒,但它對我不起作用。

如果我使用命令行工具制作標准應用程序,然后添加如下所示的 routes/contacts.js:

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

router.route('/:contactid')
  .get(function(req, res) {
    res.send('(get) It worked '+contactid);
  })

module.exports = router;

然后在 app.js 添加:

var contacts = require('./routes/contacts');

...

app.use('/contacts', contacts);

我希望http://localhost:8000/contacts/1與來自 contacts.js 的路由相匹配。 但是,我收到一個錯誤,基本上表明它不匹配 contacts.js 中的任何路由

Error: Not Found
    at Layer.app.use.res.render.message [as handle] (project1/app.js:31:15)
    at trim_prefix (project1/node_modules/express/lib/router/index.js:226:17)
    at c (project1/node_modules/express/lib/router/index.js:198:9)
    at Function.proto.process_params (project1/node_modules/express/lib/router/index.js:251:12)
    at next (project1/node_modules/express/lib/router/index.js:189:19)
    at next (project1/node_modules/express/lib/router/index.js:150:14)
    at next (project1/node_modules/express/lib/router/index.js:166:38)
    at Function.proto.handle (project1/node_modules/express/lib/router/index.js:234:5)
    at Layer.router (project1/node_modules/express/lib/router/index.js:23:12)
    at trim_prefix (project1/node_modules/express/lib/router/index.js:226:17)

如果我使用 static 前綴添加路由,它會按預期工作:

router.get('/1', function(req, res) {
  res.send('It worked!');
});

// http://localhost:8000/contacts/1 says "It worked!"

關於我做錯了什么的任何提示?

路由器路徑是相對於安裝路徑的。 因此,您的聯系路由器將只是:

router.route('/:contactid')
  .get(function(req, res) {
    res.send('(get) It worked ' + req.params.contactid);
  })

我認為這應該工作(對我有用)

在route / contacts.js中

/* Created by matthias on 6/9/14. */
var express = require('express');
var router = express.Router();

router.get('/:contactid', function(req, res) {
        res.send('(get) It worked ' + req.params.contactid);
    });

module.exports = router;

然后在app.js中

var contacts = require('./routes/contacts');
var app = express();
app.use('/contacts', contacts);

對我有用:localhost:3000 / contacts /:3

可以預期地得到:(獲取)成功了3

幫我省了很多麻煩……終於明白了 app.js 之前正在安裝路由,隨后的中間件需要與該安裝點相關。

我希望快遞文件清楚地表明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM