Reputation: 1457
I have to send data (json object) to another webserver (java).
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?
Upvotes: 22
Views: 61549
Reputation: 8397
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.
Upvotes: 24
Reputation: 1314
Please list exact error, "this is not working..." is not very helpful to identify the issue. The code is moreover fine with minor issues.
var http = require("http");
var querystring = require("querystring");
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);
The only thing to care about is, there should be a server at www.javaserver.com:8070 to give response for /login for data being POST'ed in this case the login credentials.
Upvotes: 3