Node.js / Express.js将POST请求转发到另一个域

时间:2018-02-04 01:17:57

标签: javascript node.js express

我在域example1.com的express.js应用中有一条路线:

router.post('/messages/add', (req, res) => {
  let message = new Message();
  message.title = req.body.title;
  message.body = req.body.body;
  message.save(err => {
    if(err) {
      return res.json({ success: false });
    } else {
      return res.json({ success: false });
    }
  });
});

如何将邮件传递到域example2.com上另一个快速应用程序的终端?

更新

使用request建议的YouneL模块更新了代码。 example2.com收到一个空对象:

更新2

终于搞定了。不得不在form:formData选项中添加formData:formData而不是request.post()

服务器/域1:

router.post('/messages/add', function (req, res) {
  let formData = {
    title: req.body.title,
    body: req.body.body
  }

  request.post({
    url:'http://example2.com/api/messages/add',
    form:formData}, function optionalCallback(err, httpResponse, body) {
      if (err) {
        return console.error('upload failed:', err);
      }
      console.log('Upload successful!  Server responded with:', body);
    });
});

服务器/域名2:

router.post('/contacts/add', function (req, res) {
    let message = new Message(); // Mongoose model
    message.title = req.body.title;
    message.body = req.body.body;        

    req.checkBody('title', 'Title is required').notEmpty();
    req.checkBody('body', 'Body is required').notEmpty();
    let errors = req.validationErrors();
    if (errors) {
        res.json({ success: false, msg: errors });
    } else {
        contact.save(function (err) {
            if (err) {
                console.log(err);
                res.json({ success: false, msg: 'Failed to add message' });
            } else {
                res.json({ success: true, msg: 'Message added' });                  
            }
        });
    }
});

1 个答案:

答案 0 :(得分:3)

您可以使用request模块向example2.com发送另一个帖子请求,这是一个示例:

router.post('/messages/add', (req, res) => {

    let message = new Message();
    message.title = req.body.title;
    message.body = req.body.body;
    message.save(err => {

        if (err) {
            return res.json({ success: false });
        }

        // post data to example2.com
        request.post({ url:'example2.com', form: req.body }, (err, httpResponse, body) => { 

            if (err) {
                return res.json({ success: false, msg: 'cannot post to example2.com' });
            }

            res.json({ success: true });

        });


    });

});