Jordan Choo
Jordan Choo

Reputation: 75

How to apply policies to errors?

I have a controller called "user" and an action called "signup" and then I have a policy which is called "stripSlashes" with the following code:

module.exports = function(req, res, next) {
  if(req.url.substr(-1) === '/' && req.url.length > 1){
    res.redirect(req.url.slice(0, -1), 301);
  }
  else {
    next();
  }
};

What I am trying to do is whenever http://localhost:{{port}}/user/signup/ is visited it will strip the slashes and redirect to: http://localhost:{{port}}/user/signup That works perfectly!

Except, whenever I try and visit http://localhost:{{port}}/user/signup///// for example it just throws a 404 and doesn't even run through any of the policies that I set in config/policies.js

So, my question is how do I apply my custom policies to EVERYTHING including error pages (i.e. 404s)

Thanks in advanced!


Policies.js for reference:

module.exports.policies = {

  '*': ['flash', 'stripSlashes', 'wwwRedirect'],

  user: {
    edit: ['flash', 'isAuthenticated', 'stripSlashes', 'wwwRedirect'],
    update: ['flash', 'isAuthenticated', 'stripSlashes', 'wwwRedirect'],
    show: ['flash', 'isAuthenticated', 'stripSlashes', 'wwwRedirect'],
    index: ['flash', 'isAuthenticated', 'stripSlashes', 'wwwRedirect'],
    destroy: ['flash', 'isAuthenticated', 'stripSlashes', 'wwwRedirect'],
  },


}

Upvotes: 1

Views: 53

Answers (1)

Chad
Chad

Reputation: 2289

A policy has to match a route for the policy to be applied. If you want to apply this rule to all api endpoints then you can use an express custom middleware for that. See the stack overflow answer here: Modify response header with sails.js for implementing HSTS

Upvotes: 1

Related Questions