【问题标题】:why does express middleware not working in separate files为什么快递中间件不能在单独的文件中工作
【发布时间】:2021-08-06 18:47:52
【问题描述】:

我想将我的路由器分解为单独的文件,而不是将所有 API 路由保存在一个文件中。因此,我尝试使用中间件识别用户 URL,并根据您在下面看到的 url 调用 api,但中间件功能不起作用。如何解决?

//这里是 INDEX.jS 文件代码

const express = require("express");
const dotenv = require("dotenv");

const app = express();

const PORT = process.env.PORT || 7000;
app.listen(PORT);

app.use("/users", require("./routes/users/users"));

//=============================================== ==============

//这里是 users.js 文件代码

const express = require("express");`enter code here`
const router = require("express").Router();


express().use(selectApi);

  function selectApi(req, res, next) {

console.log("this line also not executing") 


  switch(req.originalUrl){
      case '/':
          // calling api here from a nother separate file

      case '/user/:id'
         // calling api here from a nother separate file
  }
}



module.exports = router;

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    Express.js Routing Guide 中有一个示例。我已经稍微修改了它以适合您的示例。

    users.js

    var express = require('express')
    var router = express.Router()
    
    // middleware that is specific to this router
    router.use(function timeLog (req, res, next) {
      console.log('Time: ', Date.now())
      next()
    })
    // define the home page route
    router.get('/', function (req, res) {
      // calling api here from a nother separate file
    })
    
    router.get('/user/:id', function (req, res) {
      // calling api here from a nother separate file
    })
    
    module.exports = router
    

    index.js

    const express = require("express");
    const dotenv = require("dotenv");
    
    const app = express();
    
    const PORT = process.env.PORT || 7000;
    app.listen(PORT);
    
    app.use("/users", require("./routes/users/users"));
    
    

    【讨论】:

    • 我用您的解决方案解决了我的问题。有效 。谢谢
    • @DilumHarshana 乐于助人。如果此答案解决了您的问题,如果您将其标记为已接受,我将不胜感激。谢谢!
    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多