如何将 post 请求从 express.js 发送到另一台服务器(java)? [英] how to send Post request from express.js to another server ( java)?

查看:12
本文介绍了如何将 post 请求从 express.js 发送到另一台服务器(java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将数据(json 对象)发送到另一个网络服务器(java).

I have to send data (json object) to another webserver (java).

这是我的 node.js 代码

This is my node.js code

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

这不起作用.我该怎么做?

This is not working. How can I do this?

推荐答案

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

You are repeating req, and res variables for the post request. I have updated your code and tested it working with 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);

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

Please update the request host and path in the code to the values you need. Let me know if it still doesn't work for you.

这篇关于如何将 post 请求从 express.js 发送到另一台服务器(java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆