如何从node.js发送Post请求到另一个服务器(java)?

sil*_*abu 10 post request node.js

我必须将数据(json对象)发送到另一个webserver(java).

这是我的node.js代码

var express = require('express');

var app = express();

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

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

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

});

app.listen(8090);
Run Code Online (Sandbox Code Playgroud)

这不起作用.我怎样才能做到这一点?

vmx*_*vmx 16

您正在重复请求的req和res变量.我已经更新了您的代码,并使用requestb.in对其进行了测试

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: 'requestb.in',
    port: 80,
    path: '/nfue7rnf',
    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);
Run Code Online (Sandbox Code Playgroud)

请将代码中的请求主机和路径更新为您需要的值.如果它仍然不适合你,请告诉我.