How to use custom route middleware with Sails.js? (ExpressJS)

孤人 提交于 2019-12-01 03:25:21

You can use policies to achieve this. Save your isAjax function as isAjax.js under your api/policies folder, and change it to just use module.exports instead of module.exports.isAjax. Then in your config/policies.js file, you can specify which controllers/actions to apply the policy to--to run isAjax for every route, just do:

'*':'isAjax'

in that file.

I had the same issue of figuring out how to make use of middlewares. They are basically defined in the config/policies.js.
So, if you want to use middlewares(aka policies) like old style, you can do the following (this may not be the nicest way):

// config/policies.js
'*': [ 
  express.logger(),
  function(req, res, next) {
    // do whatever you want to
    // and then call next()
    next();
  }
]

However, the real sailjs way is to put all such policies in api/policies/ folder

To add compress middleware of express, I find this thread and

sails-middleware-example-issue are very usefull.

  1. install express local: npm install express
  2. load express: var exp = require('express')
  3. add customMiddleware in $app_dir/config/local.js
express: {
    customMiddleware: function (app) {
      console.log("config of Middleware is called");
      app.use(exp.logger());
      app.use(exp.compress());
      app.use(function (req, res, next) {
        console.log("installed customMiddleware is used");
        next();
      })
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!