I am doing http request in nodejs, but the request never ends and proceed to do its following code. it only prints out "response end", but never "request end". Why will it behave like this?
const post_data = JSON.stringify({
'username': username,
'org': orgName,
'peers': peers,
'channelName': channelName,
'chaincodeName': chaincodeName,
'fcn': fcn,
'args': args
});
var post_options = {
host: 'localhost',
port: '3000',
path: '/cc/write',
method: 'POST',
headers: {
"content-type": "application/json",
"Content-Length": Buffer.byteLength(post_data)
}
};
var post_req = http.request(post_options, function (res) {
console.log("connected");
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
ccResponse = chunk;
});
res.on('end', function () {
console.log('response end')
});
});
// post the data
post_req.write(post_data);
post_req.on('end', function () {
console.log('request end');
});
post_req.on('finish', function () {
console.log('request end');
});
post_req.end();
console.log("Random thing");
There is an extra bracket right above the last line console.log("Random thing");
After removing that bracket the code produced this log:
Random thing
request end
connected
Response: {"error":"Not Found"}
response end
As you can see there is 'request end' in the log.
It was run with node v11.13.0.
Please let me know if it doesn't help.
The actual code that I used:
const http = require('http');
const post_data = JSON.stringify({
'username': 'username',
'org': 'orgName',
'peers': 'peers',
'channelName': 'channelName',
'chaincodeName': 'chaincodeName',
'fcn': 'fcn',
'args': 'args'
});
var post_options = {
host: 'localhost',
port: '3000',
path: '/cc/write',
method: 'POST',
headers: {
"content-type": "application/json",
"Content-Length": Buffer.byteLength(post_data)
}
};
var post_req = http.request(post_options, function (res) {
console.log("connected");
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
ccResponse = chunk;
});
res.on('end', function () {
console.log('response end')
});
});
// post the data
post_req.write(post_data);
post_req.on('end', function () {
console.log('request end');
});
post_req.on('finish', function () {
console.log('request end');
});
post_req.end();
console.log("Random thing");
Related
I am learning to use http post and trying to wait for it to end using promise. But I can't get it to work, please help:
var http = require('http');
const auth = () => {
var post_data = JSON.stringify({
"username": "aaa",
"password": "bbb"
});
const options = {
host: 'http://1.1.1.1',
path: '/v1/authentication',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
var body = '';
res.on('data', d => {
body += chunk;
});
res.on('end', function() {
console.log("Response body", body);
});
});
req.on('error', error => {
console.error("error", error);
});
req.write(post_data)
req.end();
return Promise.resolve("!!");
};
exports.helloWorld = (req, res) => {
let message = req.query.message || req.body.message || 'Hello World!';
return auth().then((res)=>{
res.status(200).send(res);
});
};
Entry point is the hellWorld function. What should I do to wait for the http post to finish and get the response result using promise?
here i did some for get api call.
try {
const auth = () => {
return new Promise((resolve, reject) => {
const options = {
host: 'api.github.com',
path: '/orgs/nodejs',
port: 443,
method: 'GET',
headers: {
'User-Agent': 'request'
}
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', d => {
resolve(d)
});
});
req.on('error', error => {
console.error("error", error);
});
req.end();
})
};
const data = await auth()
console.log('should execute first', data)
console.log('should executed after http call')
} catch (e) {
console.log(e)
}
you can modify above code with your, just you have to wrap your http call inside Promises.
comment down if any its a solution, and mark as a solution
I have middleware (API calls, not part of a route) which I want to use in a callback response.
// MIDDLEWARE EXAMPLE
var postInvoice = function(req, res){
function request(callback) {
var path='/xxx?';
var data = querystring.stringify( {
'action' : 'xxx',
'appkey' : 'xxx'',
'fromapi' : 'xxx',
'fromapiuser' : 'xxx',
'username' : 'xxx',
'shipmethod' : 'TEST',
'shipping' : '0',
'taxes' : '0'
});
var options = {
port: 443,
host: xxx,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
var postRequest = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Invoice Response: ' + chunk);
});
});
postRequest.write(data);
}
request(function(responseData) {
console.log(responseData);
});
}
I need to access the response in another route (which itself includes callback via API)
app.get('/result', function(req, res){
var resourcePath = req.param('resourcePath');
function request(callback) {
var path = resourcePath
var options = {
port: 443,
host: xxx,
path: path,
method: 'GET'
};
var postRequest = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
jsonRes = JSON.parse(chunk);
return callback(jsonRes);
});
});
postRequest.end();
}
request(function(responseData) {
console.log(responseData);
// this is where I invoke the middleware,
if(some response condition is met) {
postinvoice();
}
res.render('result', {
check: check,
response: checkout_msg
});
});
});
I'm able to view the 'Invoice Response' in console, but I cannot manipulate it in the /result route. I'd like to be able to invoke the middleware, create locals and make the locals available in /result route.
thank you,
try this
var postRequest = http.request(options, function (response) {
var body = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
body = JSON.parse(body); //if response is json
return callback(body);
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
[EDIT]
I figured it out. The code ends up like this:
//getTrelloJSON.js
var request = require('request');
'use strict';
function getProjJSON(requestURL, callback){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
callback(data);
}
});
}
module.exports.getProjJSON = getProjJSON;
And
//showData.js
var getJSON = require('./getTrelloJSON');
getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
var lists = result.lists;
console.log(lists);
});
I run node showData.js and it gets the json and then I can manipulate it as needed. I printed just to show it works.
[EDIT END]
I'm new to node.js and I am facing a noob problem.
This code is supposed to request a JSON from a public trello board and return an object with a section of trello's json (lists section).
The first console.log() does not work but the second does.
How do I make it wait for the completion of getProjJSON() before printing it?
var request = require('request');
'use strict';
//it fails
console.log(getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json'));
function getProjJSON(requestURL){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
//it works
console.log(data.lists);
return data.lists;
}
});
}
Node.js is all about callbacks.
And here you just not register the callbacks for data.
var client = require('http');
var options = {
hostname: 'host.tld',
path: '/{uri}',
method: 'GET', //POST,PUT,DELETE etc
port: 80,
headers: {} //
};
//handle request;
pRequest = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
console.log(chunk);
});
response.on('end',function(){
console.log("\nResponse ended\n");
});
response.on('error', function(err){
console.log("Error Occurred: "+err.message);
});
});
or here is a full example, hope this solve your problem
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`res_code: ${res.statusCode}`);
console.log(`res_header: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`res_data: ${chunk}`);
});
res.on('end', () => {
console.log('end of response');
});
});
req.on('error', (e) => {
console.error(`response error ${e.message}`);
});
//write back
req.write(postData);
req.end();
I have working code to buffer a .json file and then POST that data to a server.
fs.readFile(filePath, 'utf-8', function (err, buf) {
if(err){
reject(err);
}
else{
const req = http.request({
method: 'POST',
host: 'localhost',
path: '/event',
port: '4031',
headers: {
'Content-Type': 'application/json',
'Content-Length': buf.length
}
});
req.on('error', reject);
var data = '';
req.on('response', function (res) {
res.setEncoding('utf8');
res.on('data', function ($data) {
data += $data
});
res.on('end', function () {
data = JSON.parse(data);
console.log('data from SC:', data);
//call fn on data and if it passes we are good
resolve();
});
});
// write data to request body
req.write(buf);
req.end();
}
});
what I would like to do instead is to avoid buffering it, and just use fs.createReadStream, something like so:
fs.createReadStream(filePath, 'utf-8', function (err, strm) {
if(err){
reject(err);
}
else{
const req = http.request({
method: 'POST',
host: 'localhost',
path: '/event',
port: '4031',
headers: {
'Content-Type': 'application/json',
// 'Content-Length': buf.length
}
});
req.on('error', reject);
var data = '';
req.on('response', function (res) {
res.setEncoding('utf8');
res.on('data', function ($data) {
data += $data
});
res.on('end', function () {
data = JSON.parse(data);
console.log('data from SC:', data);
//call fn on data and if it passes we are good
resolve();
});
});
// write data to request body
req.write(strm);
req.end();
}
});
but that doesn't quite work? Is it possible to do this?
This seems to work, but not sure if it's 100% correct
const strm = fs.createReadStream(filePath);
const req = http.request({
method: 'POST',
host: 'localhost',
path: '/event',
port: '4031',
headers: {
'Content-Type': 'application/json',
}
});
req.on('error', reject);
var data = '';
req.on('response', function (res) {
res.setEncoding('utf8');
res.on('data', function ($data) {
data += $data
});
res.on('end', function () {
data = JSON.parse(data);
resolve();
});
});
// write data to request body
strm.pipe(req);
I am getting a "socket hang up" error while doing a post request. I am not able to resolve it.
sparqlQ = getSPARQLPrefix() + query_string;
console.log(sparqlQ)
var options = {
host: process.env['SESAME_HOST'],
port: process.env['SESAME_PORT'],
method: 'POST',
path:
'/openrdf-sesame/repositories/myReo?update=' +
encodeURIComponent(sparqlQ) +
'&content-type=application/sparql-results+json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/sparql-results+json',
},
};
var req = http.request(options, function(res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (error) {
console.log(error)
});
res.on('end', function () {
console.log(data)
req.end();
callback(null);
});
}).on('error', function(e) {
console.alert("Error getting sesame response [%s]", e.message);
req.end();
callback(e.message);
return
});
What am I doing wrong? Please help!
Two things to mention here.
You are not calling req.end() on your http request.
refer this documentation on the http module of node.js.
With http.request() one must always call req.end() to signify that
you're done with the request - even if there is no data being written
to the request body.
on the req.error event you are calling console.alert which i think should be console.log
Here is a sample code
http = require("http");
var options = {
host: "localhost",
port: 80,
method: 'POST'
};
var req = http.request(options, function(res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (error) { });
res.on('end', function () {
console.log(data)
req.end();
console.log(null);
});
}).on('error', function(e) {
console.log("Error getting sesame response [%s]", e.message);
req.end();
console.log(e.message);
return
});
req.end();