簡體   English   中英

Express.js 主路由器工作,但他的其他路由器沒有

[英]Express.js main router working, but others routers on him not

我在路由器上有問題。 我的主要路線/天氣工作,但他的其他路由器沒有。

應用程序.js

const express = require('express');
const weatherRoute = require('./back/routes/weatherRouter.js');

const app = express();

app.use(bodyParser.json());
app.disable('etag');
app.use('/weather', weatherRoute);

天氣路由器.js

const router = express.Router();

router.get('/', async (req, res) => {
    try {
        const wholeData = await WeatherInfo.find();
        res.json(wholeData);
    } catch (err) {
        res.json({ message: err })
    }
});

router.get('/now', (req, res) => {
  res.send("ITS NOT WORKING");
});

module.exports = router;

問題是localhost:5000/weather工作完美,但是當我想在該路由上使用其他一些路由器時,例如localhost:5000/weather/now那不起作用
任何想法我做錯了什么?

更新:

當這些路由器之間沒有其他路由器時,它可以工作。

例如

 router.get('/', async (req, res) => {
//working 
    }
    router.post('/:add', async (req, res) => {
//working
    }
    router.get('/now', async (req, res) => {
//doesnt work
    }

如果我將 /now 移到 /add 路由器上方,它會完美運行。 有人可以解釋為什么會這樣嗎?

我找到了解決方案。
路由器 position 很重要。 參考解釋我的上一個路由器沒有工作,因為另一個路由器已經抓住了他。

app.get('/:add', function (req, res) {
  // this will match all /a, /b .. including /new
  res.end('done!');
});

app.get('/now', function (req, res) {
  // this is never called
  res.end('done!!');
});

在路徑部分定義實際路徑,如router.post('/weather/now', (re, res) => { //Handel re }

暫無
暫無

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

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