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?
Methods to send response from server to client are:Using send() function. Using json() function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With