将url传递给模块

时间:2016-09-11 21:12:42

标签: javascript node.js express server

如何将url导入模块?

module.exports = function(app, Reviews, Anon, User, url){
   var url = url;

  console.log("url", url)// url is undefined
  how to get url


  function postHandler(req, res){

  }


   app.post("/individual/"+ url + "/usefulness", postHandler)
};

调用routes.js

var usefulness = require("./usefulness")(app, Reviews, Anon, User, app.locals.url) 

尝试在routes.js中执行此操作

   app.use("/*", function(req, res, next){
        app.locals.url = req.path;
        next()
    })

编辑:我也尝试在routes.js中执行app.set("url", app.locals.url)并在有用性中执行var url = app.get("url")。js

如果我不能在路由器的处理程序中访问app.locals,也许我无法访问app.locals。

你知道我不能做var usefulness = require("./usefulness")(app, Reviews, Anon, User, req.path)这样的事情,如果我可以这样做会有所帮助。

2 个答案:

答案 0 :(得分:0)

由于在请求后设置了网址的值,您可以执行以下操作

module.exports = function (app, Reviews, Anon, User) {
  return function (url) {
    app.post("/individual/"+ url + "/usefulness", function () {})
  }
}

然后在routes.js

var usefulness = require("./usefulness")(app, Reviews, Anon, User) 
// ...
app.use("/*", function(req, res, next){
   app.locals.url = req.path
   usefulness(apps.locals.url)
   next()
})

Dunno为什么你要在评论,Anon和用户上创建一个关闭

答案 1 :(得分:0)

通过app.use定义的Express中间件在达到匹配模式/*的路由之前不会执行。运行脚本时,require("./usefulness")函数将未定义的app.locals.url作为参数。

使用有效usefulness参数定义app.locals.url的唯一方法是将require行移动到回调中:

var usefulness;
app.use("/*", function(req, res, next){
    app.locals.url = req.path;
    usefulness = require("./usefulness")(app, Reviews, Anon, User, app.locals.url) 
    next();
})

仍然需要在定义/*usefulness之前达到匹配app.locals.url的端点,但app.locals.url将在生命周期内保留此req.path值申请。

希望有所帮助!