【问题标题】:In sails.js: fetch model's data from remote server在sails.js 中:从远程服务器获取模型数据
【发布时间】:2014-09-13 20:20:48
【问题描述】:

我的sails.js 应用程序嵌入在php 项目中,其中php 为sails 模型生成了一些日期。在 beforeCreate 回调或某些自定义方法中找不到获取此日期的方法。我不想使用 db 来同步 2 个模型(来自sails 的模型和来自 php 的模型)。我需要向远程 php 应用程序发送一些日期。

sails.js v.0.9.x

这是我的控制器:

module.exports = {
    index: function (req, res) {},

    create: function (req, res) {
        if ( !req.param('login') )
          throw new Error('Login is undefined');
        if ( !req.param('message') )
          throw new Error('Initial message is undefined');
        var user, thread;
        User.create({
          id: 1,
          name: req.param('login'),
          ip: req.ip
        }).done( function (err, model) {
          user = model;
          if (err) {
            return res.redirect('/500', err);
          }
          user.fetch();  // my custom method
        });

        return res.view({ thread: thread });
      }
    };

和型号:

module.exports = {

    attributes: {

        id: 'integer',

        name: 'string',

        ip: 'string',

        fetch: function (url) {

            var app = sails.express.app;
            // suggest this but unlucky :)
            app.get('/path/to/other/loc', function (req, res, next) {
                console.log(req, res)

                return next()
            });
        }
    }

};

UPD 我的解决方案

型号:

beforeCreate: function (values, next) {

    var options = 'http://localhost:1337/test',
        get = require('http').get;

    get(options, function (res) {

        res.on('data', function (data) {

            _.extend( values, JSON.parse( data.toString() ) );
            next();

        });

    }).on('error', function () {

        throw new Error('Unable to fetch remote data');
        next();

    });

}

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    Yikes--app.get 远不及你所需要的。这是在您的应用程序内部绑定路由处理程序,与请求远程数据无关。不要这样做。

    在 Node 中获取远程数据的最简单方法是使用 Request library。首先使用npm install request 将其安装在您的项目目录中。然后在模型文件的顶部:

    var request = require('request');
    

    在您的fetch 方法中:

    fetch: function(url, callback) {
    
        request.get(url, function(error, response, body) {
            return callback(error, body);
        });
    
    }
    

    注意为fetch 添加的callback 参数;这是必需的,因为请求是一个 异步 操作。也就是说,对fetch() 的调用会立即返回,但请求会花费一些时间,完成后会通过回调函数将结果返回。看到 fetch 在这一点上只是 request.get 的包装,我不确定为什么有必要将它作为模型方法,但如果 URL 基于模型实例中的某些内容,那么它会有道理。

    【讨论】:

    • 感谢您的回复。我的方式类似于 require('https').get
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多