通过在Node中发出http请求来验证表单输入

时间:2014-05-01 23:29:05

标签: javascript node.js request

我有一个提交按钮调用

的表单
exports.postUpdateProfile = function(req, res, next) {
  User.findById(req.user.id, function(err, user) {
    if (err) return next(err);
    user.email = req.body.email || '';
    user.profile.name = req.body.name || '';
    //check req.body.rescueTimeKey by making http request,
    //and parsing response to ensure the key is good
    user.profile.rescueTimeKey = req.body.rescueTimeKey;

    user.save(function(err) {
      if (err) return next(err);
      req.flash('success', { msg: 'Profile information updated.' });
      res.redirect('/account');
    });
  });
};

我想在保存配置文件之前确保req.body.rescueTimeKey有效,我已经尝试创建一个模块来执行该检查...

//rescue-time.js module

var request = require('request');
exports.validKey = function(key){
var options = {
    url: 'https://www.rescuetime.com/anapi/data?key=' + key,
    json: true
};

var cb = function callback(error, response, body){  
    if(error || body.error){
        //Key is bad, flash message and don't allow save
    }
    //key is good, save profile
};
request(options, cb);
}

正如您可能想象的那样,在进行异步调用时,我并没有完全掌握使用回调的节点样式,非常感谢重新组织此代码的任何帮助。

1 个答案:

答案 0 :(得分:1)

您要做的是在validKey函数中添加一个额外的参数,以接受我们将在请求后使用的回调。

所以你的rescue-time.js看起来像这样:

// rescue-time.js
var request = require('request');

exports.validKey = function(key, cb) {
  var options = {
    url: 'https://www.rescuetime.com/anapi/data?key=' + key,
    json: true
  };

  request(options, function (error, response, body) {
    if(error || body.error){
        cb(false)
    }
    else {
      cb(true);
    }
  });
};``

如果密钥有效,我们会返回truefalse的布尔结果。

在您的控制器中,您需要以下内容:

var rescueTime = require('./path/to/rescue-time.js');

exports.postUpdateProfile = function(req, res, next) {
  User.findById(req.user.id, function(err, user) {
    if (err) return next(err);
    user.email = req.body.email || '';
    user.profile.name = req.body.name || '';
    //check req.body.rescueTimeKey by making http request,
    //and parsing response to ensure the key is good
    user.profile.rescueTimeKey = req.body.rescueTimeKey;

    // We're sending in a callback function that will have a "valid" result as a second arg
    rescueTime.validKey(user.profile.rescueTimeKey, function(valid) {
      // check if valid returned true or false and act accordingly 
      if (!valid) {
        req.flash('error', 'invalid rescueTime key');
        res.redirect('/account');
      }
      else {
        user.save(function(err) {
          if (err) return next(err);
          req.flash('success', { msg: 'Profile information updated.' });
          res.redirect('/account');
        });
      }    
    });
  });
}; 

请记住,这些代码根本没有经过测试,但更多的是关于您需要做什么才能获得所需结果的示例。