2014-07-22 108 views
1

我的sails.js應用程序被嵌入在PHP項目中,其中PHP爲風帆模型生成一些日期。無法在beforeCreate回調或某個自定義方法中找到獲取此日期的方法。我不希望使用db來同步2個模型(模型來自PHP的帆&模型)。我需要發送一些日期到遠程php應用程序。在sails.js:從遠程服務器獲取模型的數據

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(); 

    }); 

} 

回答

2

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); 
    }); 

} 

注意添加callback參數fetch;這是需要的,因爲請求是異步操作。也就是說,fetch()的調用將立即返回,但請求需要一些時間,並且完成後它將通過回調函數將結果發回。看到fetch在這一點上只是一個圍繞request.get的包裝,我不知道爲什麼有必要將它作爲一個模型方法,但如果URL是基於模型實例內的某些東西,那麼它是有道理的。

+0

感謝您的回覆。我的方式類似於require('https')。get – shifteee

相關問題