Meteor方法在不应该触发HTTP调用时触发

时间:2016-05-24 15:54:32

标签: javascript meteor

我有一个meteor方法,用于向集合添加电子邮件地址,然后将其提交给sendgrid。

export const insertEmail = new ValidatedMethod({
  name: 'emails.insert',
  validate: new SimpleSchema({
    email: { type: String }
  }).validator(),
  run(email) {
    let isPresent = Emails.find({email: email.email}).count();

    var isEmailValid = function(address) {
      return /^[A-Z0-9'.1234z_%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(address);
    };

    if( isPresent < 1 && isEmailValid(email.email) ) {
      Emails.insert({email: email.email, ip: '1'});

      try {
        HTTP.call('POST',
          'https://api.sendgrid.com/v3/contactdb/recipients', {
            headers: {
              Authorization: "Bearer " + Meteor.settings.sendGridMarketingKey,
              'Content-Type': 'application/json'
            },
            content: '[{\"email\": \"' + email.email + '\"}]'
          }, function (error, success) {
            if (error) {
              // throw new Meteor.Error(500, error);
            } else {
              return success
            }
          });
      } catch(error) {
        // throw new Meteor.Error(500, error);
      }
    } else {
      throw new Meteor.Error(500, 'This Email is Already Added!')
    }
  },
});

电子邮件收藏的提交和添加效果很好,但我有两个问题:

1)即使它有效,我也会收到POST https://api.sendgrid.com/v3/contactdb/recipients 403(FORBIDDEN)即使我输入的电子邮件已经添加并且“已添加此电子邮件”错误被触发,也会发生这种情况。当我没有看到相应的重复添加电子邮件到我的收藏时,有谁知道为什么我收到POST错误?我天真地认为,如果我搞砸逻辑并且我在不应该调用HTTP方法时,我也会同时触发Email.insert方法,但HTTP方法似乎会自行触发即使没有email.email存在,然后提供该禁止错误。

2)我无法弄清楚如何正确地将某人的IP地址添加到集合中。我之前使用过这个命令并且它有效,但它似乎不起作用,因为它在ValidateMethod中:

var ipAddress = this.connection.clientAddress;
check(ipAddress, String);

1 个答案:

答案 0 :(得分:0)

替换:

content: '[{\"email\": \"' + email.email + '\"}]'

const content = JSON.stringify([{email: email.email}])
const options = {
     headers: {...},
     content: content
}
[...]
HTTP.call(type, url, options, function (err, data) {});

确保您的帖子数据能够正确发送。