Sai
Sai

Reputation: 2042

Sails.js - Serving sails route via express middleware

I have a sails app and the routes,static assets associated with the app are served from root and it works fine. I would like to add a express middleware so i could serve the routes and static assets in a specific path.

In order to serve the static assets i used the below inside the customMiddleware function in config/http.js,

app.use('/my/new/path', express.static(path.join(__dirname, '../client', 'dist')));

With the above in place i was able to load the static files both from the root as well as from the /my/new/path.

Now when it comes to route i'm not sure how to handle the sails route to load via express middleware using app.use, for example the home route defaults to '/' in my config/routes-client.js, instead of altering the route there i would like to use something like below which we normally use for a typical node/express app,

app.use('/my/new/path', routes); --> where routes is my server routes

Is there a way to add a express middleware to serve sails route on a specific path?

Upvotes: 0

Views: 570

Answers (2)

sgress454
sgress454

Reputation: 24958

I'm not sure why you'd want to have a prefix added automatically to your custom routes rather than just adding the prefix directly to the routes in the config/routes.js (or config-routes-client.js) file, but here goes:

// config/http.js
middleware: {
  reroute: function (req, res, next) {
    // Set the prefix you want for routes.
    var prefix = '/foo/bar';
    // Create a regex that looks for the prefix in the requested URL.
    var regex = new RegExp('^' + prefix + '(/|$)');
    // If the prefix is found, replace it with /
    if (req.url.match(regex)) {
      req.url = req.url.replace(regex, '/');
    }
    // Continue processing the request.
    return next();
  }
}

Make sure you add reroute to the middleware.order array in config/http.js. Incidentally, this will take care of static files as well.

Upvotes: 1

hlozancic
hlozancic

Reputation: 1499

This is how I do it...

Inside http.js

var express = require('express');

    module.exports.http = {
        customMiddleware: function (app) {
            app.use('/docs', express.static(path.join(sails.config.appPath, '/docs')));
        },

    ... rest of the http.js code...
    }

Of course in this example im serving docs folder from root of my app on route /docs... You addapt to your logic...

Upvotes: 0

Related Questions