如何仅在开发环境中使用Sails.js提供静态文件? [英] How do I serve static files using Sails.js only in development environment?

查看:75
本文介绍了如何仅在开发环境中使用Sails.js提供静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在生产服务器上,我们使用nginx为Sails.js应用程序提供静态文件,但是在开发环境中,我们希望Sails为我们提供静态文件.这将使我们能够跳过开发人员机器上的nginx安装和配置.

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.

我该怎么做?

推荐答案

我将向您展示如何使用用于Node.js/Express的serve-static 模块.

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

1).首先安装用于开发环境的模块:npm i -D serve-static.

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

2).在api/hooks目录内创建serve-static目录.

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

3).在先前创建的serve-static目录中创建index.js文件.

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

4).向其中添加以下内容:

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).编辑config/http.js文件并添加先前定义的中间件:

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

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

6).重新启动/运行您的应用程序,例如node ./app.js并尝试获取静态文件之一.应该可以.

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

这篇关于如何仅在开发环境中使用Sails.js提供静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆