如何将Express.js中的发帖请求发送到另一台服务器(Java)? [英] how to send Post request from express.js to another server ( java)?
本文介绍了如何将Express.js中的发帖请求发送到另一台服务器(Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须将数据(json对象)发送到另一个Web服务器(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?
推荐答案
您正在重复请求,并为发布请求重新分配变量.我已经更新了您的代码,并与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.
这篇关于如何将Express.js中的发帖请求发送到另一台服务器(Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文