如何将POST请求发送到另一个node.js服务器

时间:2016-12-06 20:22:53

标签: node.js http express

我制作2台服务器

var express = require('express');
var querystring = require('querystring');
var http = require('http');

var app = express();
app.get('/', function (req, res) {
  var data = querystring.stringify({
    username: 'myname',
    password: 'pass'
  });

  var options = {
    host: 'localhost',
    port: 8081,
    path: '/demo',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(data)
    }
  };

  var httpreq = http.request(options, function (response) {
    response.setEncoding('utf8');
    response.on('data', function (chunk) {
      console.log("body: " + chunk);
    });
    response.on('end', function() {
      res.send('ok');
    })
  });
  httpreq.write(data);
  httpreq.end();
});

app.listen(8090, function(){
    console.log('Server start on 8090');
});

第二个是

var express = require('express');
var app = express();

app.post('/demo', function(req, res){
    console.log('Body : ', req.body);
});

app.listen(8081, function(){
    console.log('Server Start on 8081');
});

我想将数据从localhost:8090发送到localhost:8081。

但是当我尝试打印req.body时,在第二服务器端它显示了我

Server Start on 8081
Body :  undefined

帮我找到解决方案。如果你有更好的代码那么这对我有好处。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您的快速服务器中未定义您的正文的原因是您没有使用body-parser中间件。 Express无法解析您在请求中指定的内容类型x-www-form-urlencoded的请求正文。同样在您的请求中,您不是通过请求正文发送数据,而是在查询字符串中发送数据,因此您的Express Route需要检查查询字符串而不是正文。

您需要让Express看起来像这样:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 1337;

app.use(bodyParser.urlencoded({ extended: true }); // Parse x-www-form-urlencoded

app.post('/demo', (req, res) => {
  console.log(`Query String: ${req.query}`);
  console.log(`Body: ${req.body}`);
});

app.listen(port, () => { 
  console.log(`Listening on ${port}`); 
});

答案 1 :(得分:0)

你可以这样做

require('request').post(
    "localhost:8081/demo", 
    {form: 
        {
            username: "name",
            password: "any"
        }
    },
    function(error, response, body){
        console.log(body);
    }
);