在sails.js中创建配置变量?

use*_*473 42 node.js express sails.js

我正在将我的应用程序从Express转换为sails.js - 有没有办法在Sails中做这样的事情?

从我app.js在Express中的文件:

var globals = {
    name: 'projectName',
    author: 'authorName'
};

app.get('/', function (req, res) {
    globals.page_title = 'Home';
    res.render('index', globals);
});
Run Code Online (Sandbox Code Playgroud)

这让我可以在每个视图上访问这些变量,而无需将它们硬编码到模板中.不知道在Sails中如何/在哪里做到这一点.

ata*_*man 92

您可以在config/文件夹中创建自己的配置文件.例如,config/myconf.js使用您的配置变量:

module.exports.myconf = {
    name: 'projectName',
    author: 'authorName',

    anyobject: {
      bar: "foo"
    }
};
Run Code Online (Sandbox Code Playgroud)

然后通过全局sails变量从任何视图访问这些变量.

在一个视图中:

<!-- views/foo/bar.ejs -->
<%= sails.config.myconf.name %>
<%= sails.config.myconf.author %>
Run Code Online (Sandbox Code Playgroud)

服务中

// api/services/FooService.js
module.exports = {

  /**
   * Some function that does stuff.
   *
   * @param  {[type]}   options [description]
   * @param  {Function} cb      [description]
   */
  lookupDumbledore: function(options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails` is not available out here
// (it doesn't exist yet)
console.log(sails);  // ==> undefined
Run Code Online (Sandbox Code Playgroud)

在模型中:

// api/models/Foo.js
module.exports = {
  attributes: {
    // ...
  },

  someModelMethod: function (options, cb) {

    // `sails` object is available here:
    var conf = sails.config;
    cb(null, conf.whatever);
  }
};

// `sails is not available out here
// (doesn't exist yet)
Run Code Online (Sandbox Code Playgroud)

在控制器中:

注意:这在策略中的工作方式相同.

// api/controllers/FooController.js
module.exports = {
  index: function (req, res) {

    // `sails` is available in here

    return res.json({
      name: sails.config.myconf.name
    });
  }
};

// `sails is not available out here
// (doesn't exist yet)
Run Code Online (Sandbox Code Playgroud)

  • 为了简化访问,您可以将配置写为`module.exports.name ='projectName';`.从配置文件导出的所有内容都将成为全局`sails.config`对象的一部分.但我仍然建议在命名空间中包装自定义配置变量,以避免意外更换重要的sails配置选项. (2认同)
  • @mikermcneil是否可以在另一个配置文件中使用配置变量(如本地设置的变量)? (2认同)