I am having trouble getting my node.js server to do an http POST request to another node.js server. I am fairly certain that the problem lies with the http library or how I am using it because I can write a small HTML page that performs the POST exactly as I want.
Here is how the server receiving the POST is set up
var server = restify.createServer({
name: 'some server',
version: "1.0.0"
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.bodyParser());
server.post('/theurl/', handler.handlePost);
server.listen(config.port, function() {
console.log("starting server on port %d", server.address().port);
});
Inside the handlePost method I am doing this:
exports.handlePost = function(req, res, next) {
console.log("body: %s", JSON.stringify(req.body));
console.log("params: %s", JSON.stringify(req.params));
}
Here is the how the server that is sending the POST is doing it (this was taken directly from the node.js http docs)
var options = {
host: '127.0.0.1',
port: 8090,
path: '/theurl/',
method: 'POST'
};
var req = http.request(options, function(res) {
ses.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<some>xml</some>");
req.end();
When I run the POST, both req.body and req.params are undefined inside the handlePost method.
But if I put the following HTML in a browser, I can post to the service just fine.
<html>
<head>
<script>
function doPost()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost:8090/theurl/",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("<some>xml</some>");
}
</script>
</head>
<body>
<button type="button" onclick="doPost()">POST data</button>
</body>
</html>
So am I doing something wrong with the node.js http library?
Well, right after I posted this I realized that one thing I was doing in the HTML version that I wasn't doing in the node.js version was setting the Content-Type on the request. If I change the options to this, it works:
var options = {
host: '127.0.0.1',
port: 8090,
path: '/theurl/',
method: 'POST',
headers: { "Content-type": "application/x-www-form-urlencoded" }
};
use the code below
var querystring = require('querystring');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
Make sure that you have added these things in your app.js file:
var bodyParser = require('body-parser'); // npm i body-parser
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Related
I am getting Status 400 error with below Nodejs code
This is trying to send https post request to abc.xyz on port 12345
I am unable to figure what is wrong here.
Although I am not Nodejs expert
const https = require('https');
const options = {
hostname: 'abc.xyz',
port: 12345,
path: '/test/',
method: 'POST',
json: true,
rejectUnauthorized: false
};
exports.handler = (event, context, callback) => {
const req = https.request(options, (res) => {
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
// console.log('Body: ' + body);
}
callback(null, body);
});
});
req.on('error', callback);
// req.write(JSON.stringify(event.data));
//console.log(event.data);
req.end();
};
You can only host these applications on localhost when testing.
You also need an app.listen(LOCALHOST:PORT);
A simple Nodejs tutorial will give you a deeper explanation.
This is a simple node server running on localhost 8080, no one else can see it.
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
I'm trying to get an access token via a POST request from the Twitch API but my http.request is never executing (I don't think) and I can't figure out why.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var https = require('https');
var querystring = require('querystring');
var authInfo = require('./authInfo.json');
app.get('/twitch/auth', function(req, res) {
res.send("auth page");
var data = querystring.stringify({
client_id: authInfo.clientID,
client_secret: authInfo.clientSecret,
grant_type: "authorization_code",
redirect_uri: authInfo.redirectURI,
code: req.query.code,
state: 12345
});
var options = {
host: 'api.twitch.tv',
port: 443,
path: '/kraken/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
}
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
console.log(d);
});
});
req.on('error', (e) => {
console.log(e);
});
req.end();
});
app.listen(port, function() {
console.log('Point browser to: http://localhost:' + port);
});
PS I've omitted the some code for brevity but I get back an authorization code successfully.
I solved my problem. I wasn't writing data to the body.
...
req.write(data);
req.end();
});
...
sample code:
// index.pug
p #{polls}
// apiendpoint
http://localhost:8080/api/polls
// routes file (index.js):
Here, how do I make get request to the api, and pass the retrieved result from api(locals) to polls variable while rendering the profile.pug
app.route('/profile')
.get(isLoggedIn, function (req, res) {
res.render('profile', {'polls': passvaluehere});
});
});
You can also use **http** module like this
var http = require('http');
var options = {
host: 'localhost',
path: '/api/polls',
port: '80',
method: 'GET'
};
var req = http.request(options, response);
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
res.render('profile', {'polls': str});
});
req.end();
I am trying to build a network of IOTs.
On my node server, I am listening for WAN/LAN HTTPS requests. Upon receipt, I would like it to send out a HTTP request to an independent IOT. I have gotten a simple example up:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
var a = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Can anybody guide on sending out a http POST request to http://192.168.1.137/?pin=ON1, along with the "hello world" in the above code?
The docs for http.request include a sample of how to send a POST request. Here it is modified to send the POST request you ask for.
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: '192.1681.137',
port: 80,
path: '/?pin=ON1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
#include <http://192.168.1.137/?pin=ON1>
requesting=true
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
cout << "hello world">
var a = https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
This is my code I have written .
var querystring = require('querystring');
var http = require('http');
var body = querystring.stringify({
B1: 'Submit',
RollNumber: 12569
});
var request = http.request({
host: '14.139.56.15',
port: 443,
path: '/scheme12/studentresult/details.asp',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body)
}
}, function(res,err) {
if(err){
console.log(err);
}
console.log('Getting response..');
var resp = '';
res.on('data', function(data) {
resp += data;
});
res.on('end', function() {
console.log(resp);
});
res.on('error', function(err) {
winston.error(err);
});
request.write(body);
request.end();
});
It is giving me this error
Error: read ECONNRESET
I am doing this for the first time and don't know whether I am doing this right or not . You can visit the link and check it out . I need to get the data out of this form
You're trying to submit an HTTP request to a site listening on an HTTPS port (443). Change var http = require('http'); to var http = require('https'); (and the variable name to match if you like).