我必须将数据(json对象)发送到另一个Web服务器(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);
这是行不通的。我怎样才能做到这一点?
您正在重复请求,并为发布请求重新分配变量。我已经更新了您的代码并与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);
请将请求主机和代码中的路径更新为所需的值。让我知道它是否仍然对您不起作用。