2

I have a route in my express.js app on a domain example1.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 });
    } else {
      return res.json({ success: false });
    }
  });
});

How do I pass the message to another express app's endpoint on a domain example2.com?

UPDATE

Updated the code using the request module suggested by YouneL. example2.com receives an empty object:

UPDATE 2

Finally got it working. Had to put form:formData instead of formData:formData in the request.post() options.

Server/domain 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);
    });
});

Server/domain 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' });                  
            }
        });
    }
});
mikebrsv
  • 1,890
  • 2
  • 24
  • 31
  • Seems like a duplicate to https://stackoverflow.com/questions/11355366/how-to-redirect-users-browser-url-to-a-different-page-in-nodejs – SteveB Feb 04 '18 at 01:25
  • No, it's not. My question is specific for the express.js package. – mikebrsv Feb 04 '18 at 01:30
  • It would work in express but if you want express specific, https://stackoverflow.com/questions/28352871/in-express-how-do-i-redirect-a-user-to-an-external-url – SteveB Feb 04 '18 at 01:32
  • I appreciate your inputs, but I don't need to redirect a user to another URL. What I need is to make a post request to another domain. – mikebrsv Feb 04 '18 at 01:38
  • So you want to take the request and call another endpoint and wait for the response like a proxy? Given the second domain, I was assuming a redirect would work. – SteveB Feb 04 '18 at 01:40

1 Answers1

4

You could use request module to send another post request to example2.com, here is an example:

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

        });


    });

});
YouneL
  • 8,152
  • 2
  • 28
  • 50
  • For some reason doesn't post to example2 and returns a warning `Resource interpreted as Document but transferred with MIME type application/json`. – mikebrsv Feb 04 '18 at 02:59
  • Try to set the Content-type header to text/html, here is how to do that: `request.post({ url:'example2.com', headers: { 'Content-type': 'text/html' }, form: req.body }...` – YouneL Feb 04 '18 at 03:21
  • Nothing changes – mikebrsv Feb 04 '18 at 03:28
  • Try to change it to `headers: { 'Accept': 'text/html' }`, if it doesn't work, you need to change the content-type header of the response to text/html, in `example2.com` server – YouneL Feb 04 '18 at 03:39
  • Okay, I managed to get rid of the warning. There's still an issue though. The request from the `example1` sends the data, but the `example2` endpoint can't handle the request and receives `undefined`s, yet the server seems to receive the data. I `console.log`ed `req.body` on the `example2` side and it looks like this: `{ <...>, '_doc[title]': 'testtitle', '_doc[body]': 'testbody' }`. I'm not sure, maybe I just handle it wrong on the `example2` side. – mikebrsv Feb 04 '18 at 04:40
  • The code to post the data on the `example2` side is pretty much the same as I already cited in the first post. – mikebrsv Feb 04 '18 at 04:43