简体   繁体   中英

Node.js request module can't POST to external URL

I have a web app that collects data from sensors. Sensors send data through POST requests to my webapp at example.com .

For debugging purposes, I need to create an extra layer between the sensors and the webapp.

I have created an extra little webapp that all that does is to take the incoming POST requests to example.com and forward it to the webapp, now responding to a different URL, say example2.com .

So, before it was:

sensors -> example.com (webapp)

now it is:

sensors -> example.com -> example2.com (webapp)

In this way I am able to see what's the webapp response to the sensors and log it.

In order to make this work I have used the request module . Everything works fine when I am testing it on my local machine (my extra layer listens on localhost:3000 and the webapp listens on localhost:3001 ), but as soon as I make it point to an external URL the answer I get back is a 404 Not Found , even though if I POST directly to example2.com everything works as expected.

Here is my module:

var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
var cuid = require('cuid');
var url = require('url');
app.use(bodyParser.text({ type: '*/*' }));

app.post('/', function (req, res) {

  // immediately send 200 OK to the client
  res.send('ok');

  // add a unique ID
  if (!req.headers['x-request-cuid']) {
    req.headers['x-request-cuid'] = cuid();
  }

  var log_string = req.headers['x-request-cuid'] + "," + new Date().toISOString();

  // filter empty requests
  var reqbody = req.body;
  if(typeof reqbody !== 'string'){
    return res.send('empty body');
  }
  // Configure the request
  var options = {
    method: 'POST',
    url: 'http://example.com', // <- if I put localhost:3001 (the port I put my webapp to listen on) here, it works
    headers: req.headers,
    body: reqbody
  };

  // Start the request
  request(options, function (error, response, body) {

    log_string += "," + new Date().toISOString() + "," + response.statusCode + "," + response.statusMessage + "," + response.body;
    console.log(log_string);
  });

});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

If it helps, I am working on Google App Engine, so everything gets deployed to Google App Engine.

EDIT: clarification on "does not work"

According to this documentation , your app has to listen to port 8080 .

The App Engine front end will route incoming requests to the appropriate module on port 8080. You must be sure that your application code is listening on 8080.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM