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
Related
I'm making an http post request to my express web server sending dummy data as json. It correctly receives the request and can send back a json object, but for some reason it can't manage to access the post request body.
I'm using this code for express:
const express = require('express');
const app = express();
const port = 3000;
app.post('/test', (req, res) => {
console.log(req.body);
res.json({"some": "thing"});
});
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
});
And this is the code of the request:
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
json: {
url: "https://www.nothing.com",
name: "hello"
}
}, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.end()
As you can see I'm running this locally. The client receives a status code 200 and the json {"some": "thing"} sent by the server, but the server gets "undefined" from req.body. I tried using:
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
url: "https://www.nothing.com",
name: "hello"
})
instead of json directly in the request options, but to no avail. I even tried using app.use(express.json()); as someone suggested.
What is the problem?
Apparently the way I was doing the post request was not correct, I had to send the body in a separate line with req.write(), like this:
const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
url: "https://www.nothing.com",
name: "hello"
});
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
})
})
req.on('error', error => {
console.error(error);
})
req.write(data); //<--- this line
req.end();
You have to add body-parser middleware http://expressjs.com/en/resources/middleware/body-parser.html
req.body empty on posts
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).
I am using node wget to download files from URL and I am getting this error.
If I use simple wget command to download files it working fine, but I want download file from node module
here is my code
var wget = require('wget');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, response) {
var options = {
protocol: 'https',
host: 'raw.github.com',
path: '/Fyrd/caniuse/master/data.json',
proxy: 'http://host:port',
method: 'GET'
};
var req = wget.request(options, function(res) {
var content = '';
if (res.statusCode === 200) {
res.on('error', function(err) {
console.log(err);
});
res.on('data', function(chunk) {
content += chunk;
});
res.on('end', function() {
console.log(content);
});
} else {
console.log('Server respond ' + res.statusCode);
}
});
req.end();
req.on('error', function(err) {
console.log(err);
});
response.render('index', { title: 'Express' });
});
module.exports = router;
I stumble upon this question. This is probably caused by the proxy not supporting HTTPS. Try a proxy that supports HTTPS and the problem should be solved.