How do I serve static files using Sails.js only in

2019-07-26 16:26发布

On production servers, we use nginx to serve static files for our Sails.js application, however in development environment we want Sails to serve static files for us. This will allow us to skip nginx installation and configuration on dev's machines.

How do I do this?

1条回答
贪生不怕死
2楼-- · 2019-07-26 17:00

I'm going to show you how you could solve this using serve-static module for Node.js/Express.

1). First of all install the module for development environment: npm i -D serve-static.

2). Create serve-static directory inside of api/hooks directory.

3). Create the index.js file in the serve-static directory, created earlier.

4). Add the following content to it:

module.exports = function serveStatic (sails) {

  let serveStaticHandler;

  if ('production' !== sails.config.environment) {
    // Only initializing the module in non-production environment.
    const serveStatic = require('serve-static');
    var staticFilePath = sails.config.appPath + '/.tmp/public';
    serveStaticHandler = serveStatic(staticFilePath);
    sails.log.info('Serving static files from: «%s»', staticFilePath);
  }

  // Adding middleware, make sure to enable it in your config.
  sails.config.http.middleware.serveStatic = function (req, res, next) {
    if (serveStaticHandler) {
      serveStaticHandler.apply(serveStaticHandler, arguments);
    } else {
      next();
    }
  };


  return {};

};

5). Edit config/http.js file and add the previously defined middleware:

module.exports.http = {
  middleware: {
    order: [
      'serveStatic',
      // ...
    ]
  }
};

6). Restart/run your application, e.g. node ./app.js and try to fetch one of static files. It should work.

查看更多
登录 后发表回答