I have this code I wrote for my server:
var http = require("http");
var url = require("url");
var routing = require("./RoutingPath");
var email = require('./NewServices.js');
var config = require ('./config.js');
function start() {
function onRequest(request, response) {
var path = url.parse(request.url).pathname;
var params = url.parse(request.url,true).query;
if (request.url === '/favicon.ico')
{
}
else
{
var data;
request.on('data', function(chunk) {
console.log("Received body data:");
console.log(chunk.toString());
data = chunk.toString();
});
routing.Route(path.toLowerCase(), params, data ,function(recordset){
response.writeHead(200, {"Content-Type": "application/json"});
if (recordset != null)
{
if (recordset.respondMessage == "GeneralSqlError")
{
var msg = JSON.stringify(recordset, null, 4);
console.log(msg);
email.SendEmailErrorNotify(msg, function(err){
if(err)
console.log(err);
});
}
else
{
console.log(JSON.stringify(recordset, null, 4));
}
response.write(JSON.stringify(recordset, null, 4));
}
response.end();
console.log();
});
}
}
http.createServer(onRequest).listen(8888);
console.log("Server has started!");
}
Sometimes the post request has data inbody. When there's a body I need to use it and process data.
The variable "data" in the following line should have data when it called:
routing.Route(path.toLowerCase(), params, data ,function(recordset){
...
How can I know if I have body?
Related
We are using method called flask_api which has the parameter.
Our need is, we need to pass that parameter inside request.post
Can anyone please help as we are beginners in node.js
async flask_api(turnContext){
var res;
var fs = require('fs');
var request = require('request');
var formData = {image1: fs.createReadStream('D:/my_app/demo.png')}
var json_body = "" ;
var obj_value= ""
function initPromise(turnContext)
{return new Promise(function(resolve,reject)
{
console.log("print turn context",turnContext); //we are getting the value in turncontext
console.error('before post call...:1');
request.post({url:'http://127.0.0.1:5002/',formData: formData}, function(err, httpResponse, body)
{
if (err) {
console.log("response", reject(err));
return JSON.stringify(err);
}
else{
while(1==1){
if(body != undefined){
break;
}
}
json_body = JSON.parse(body);
resolve([json_body,turnContext]);//here we are not able to get the turncontext
}
});
})
}
Try using this:
var req = request.post({ url: 'http://127.0.0.1:5002/' }, (err, resp, body) => {
if (err) {
res.status(500).send(err);
} else {
res.send(resp);
}
});
var form = req.form();
form.append('file', fs.createReadStream('D:/my_app/demo.png'));
In your case:
async flask_api(turnContext){
var res;
var fs = require('fs');
var request = require('request');
var formData = {image1: fs.createReadStream('D:/my_app/demo.png')}
var json_body = "" ;
var obj_value= ""
var tempContext;
function initPromise(turnContext)
{return new Promise(function(resolve,reject)
{
tempContext = turnContext;
console.log("print turn context",tempContext); //we are getting the value in turncontext
console.error('before post call...:1');
request.post({url:'http://127.0.0.1:5002/',formData: formData}, (err, httpResponse, body) =>
{
if (err) {
console.log("response", reject(err));
return JSON.stringify(err);
}
else{
while(1==1){
if(body != undefined){
break;
}
}
json_body = JSON.parse(body);
resolve([json_body,tempContext]);//here we are not able to get the turncontext
}
});
})
}
Try this. Note that I refactored your code (how I would have done it).
Server (for test purposes)
var http = require('http');
var querystring = require('querystring');
var server = http.createServer().listen(8124);
server.on('request', function(request,response) {
if (request.method == 'POST') {
var body = '';
// append data chunk to body
request.on('data', function (data) {
body += data;
});
// data transmitted
request.on('end', function () {
var post = querystring.parse(body);
console.log(post);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(JSON.stringify('body\n'));
});
}
});
console.log('server listening on 8124');
Client
function initPromise(turnContext) {
var res;
var fs = require('fs');
var request = require('request');
var formData = {image1: "hello"}
var json_body = "" ;
var obj_value= "";
return new Promise(function(resolve,reject) {
console.log("print turn context",turnContext); //we are getting the value in turncontext
console.error('before post call...:1');
request.post({url:'http://localhost:8124/',formData: formData}, function(err, httpResponse, body) {
if (err) {
reject(err);
}
else{
if (body != undefined) {
json_body = JSON.parse(body);
resolve([json_body,turnContext]); //here we are not able to get the turncontext
} else {
reject('body undefined');
}
}
});
});
}
async function flask_api(turnContext) {
var result = initPromise(turnContext);
console.log("result", result);
result.then(
// fulfillment
function (val) { //this is where you get the value passed to resolve()
console.log(val);
}).catch(
//log the rejection reason
(reason) => {
console.error(reason);
}
);
}
flask_api({test: 'hello'});
The result on the client side is:
print turn context { test: 'hello' }
before post call...:1
result Promise { <pending> }
[ 'body\n', { test: 'hello' } ]
Note:
That line of code return JSON.stringify(err); isn't necessary. The callback in a promise is not expecting any return unless you want to use it for flow control purposes.
if body is indeed undefined, you will have an infinite loop.
Try using this:
This will work for the latest node.js versions.
async initPromise(turnContext)
{
var res;
var fs = require('fs');
var request = require('request');
var formData1 = {image1: "Hello"};
var path = require('path')
var base_dir=path.dirname(path.dirname(__filename))
console.log(path.join( base_dir, "resource", "output.png"));
var image_name = path.join( base_dir, "resource", "output.png")
var formData = { image1: fs.createReadStream(image_name) };
var json_body = "" ;
var obj_value= "";
return await new Promise(function(resolve,reject)
{
console.log("pls work",turnContext);
//\var turnContext1 = turnContext;
//\console.log(typeof(turnContext));
console.error('before post call...:1');
request.post({url:'http://127.0.0.1:5002/',formData: formData}, (err, httpResponse, body) =>
{
console.log("formdata....body....",formData);
console.log("inside request post");
if (err) {
reject(err);
}
else{
if (body != undefined) {
json_body = JSON.parse(body);
console.log("response inside", json_body);
resolve([json_body,turnContext]); //here we are not able to get the turncontext
} else {
reject('body undefined');
}
}
});
});
}
async flask_api(turnContext) {
var result = await this.initPromise(turnContext);
console.log("result", result);
console.log("result1", result[0]);
console.log("result2", result[1]);
}
I'm trying to read data sent to node.js server.
Client side:
const sendToDB =(date)=> {
var xhttp = new XMLHttpRequest();
var d = JSON.stringify(date);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(d);
}
};
xhttp.open("POST", "api/info", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(d);
}
and the server:
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log(req.body.date);
});
res.end();
});
server.listen(3001);
how to receive data sent with xhttp.send(d) in node js server ?
var server = http.createServer(function(req, res) {
if(req.method == "POST"){
var clientData = '';
req.on('data', function (chunk) {
clientData+=chunk;
});
req.on('end',function(){
console.log(JSON.parse(clientData));
})
}
res.end();
});
you should use the header "Content-Type", "application/json" as you send some json data.
make sure you send a such an object :
{
date: {
foo: bar
}
}
as your server is expecting it in the body req.body.date
I am trying to perform a GET request to an API and return the data from the API response to the client. I think the client receives a response before the GET request to the API finishes. How can I change the code to ensure that the response from the API is passed on to the client?
if (request.method == 'POST' && request.url == '/locationdata') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var formattedLocation = body.replace(/[\[\]']+/g, '');
var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;
response.writeHead(200, { 'Content-Type': 'application/json' });
var apiData = '';
var apirequest = function () {
https.get(urlAPI, function (response) {
response.on('data', function (data) {
apiData += data;
});
response.on('end', function () {
console.log(apiData);
return apiData;
});
});
}
response.end(apirequest);
});
return;
}
You are ending the response to the client before you get all the data from the api. Moving the response.end() call up to the end of the api response should fix it:
if (request.method == 'POST' && request.url == '/locationdata') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var formattedLocation = body.replace(/[\[\]']+/g, '');
var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;
response.writeHead(200, { 'Content-Type': 'application/json' });
var apiData = '';
https.get(urlAPI, function (apiResponse) {
apiResponse.on('data', function (data) {
apiData += data;
});
apiResponse.on('end', function () {
console.log(apiData);
// send response to browser after we get all the data from the api
response.end(apiData);
});
});
// remove this because we moved it up
//response.end(apirequest);
});
return;
}
I've set up a NodeJS server which can be accessed by a client. Every once in a while it's necessary to let the server connect to a second server and feed the information retrieved back to the client.
Connecting to the second server is the easy part, but to be honest I have no idea how to send it back to the client. res.write seems to be forbidden during the connection with the second server.
The connection from the client is handled by handleGetRequest. The connection with the second server starts at http.get.
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
http.get(OPTIONS, function(secget) {
resget.on('data', function(chunk) {
// either store 'chunk' for later use or send directly
});
}).on('error', function(e) {
console.log("Error " + e.message);
});
} else {
res.writeHead(404);
}
res.end('Closed');
};
server.listen(8000);
How do I send the chunk from http.request to the client?
I thinks passing the callback to the handleGetRequest will fix this issue:
if (req.method === 'GET') {
handleGetRequest(url_parsed, function (err, response) {
if (err) {
return res.sendStatus(500);
}
res.json(response);
});
} else {
res.end('Method not supported');
}
handleGetRequest = function (url_parsed, callback) {
// OPTIONS ...
http.get(OPTIONS, function(resget) {
var data = '';
resget.on('data', function(chunk) {
data += chunk;
});
resget.on('end', function() {
callback(null, data);
});
}).on('error', function(e) {
callback(e);
});
}
Thanks to #TalgatMedetbekov for the suggestions. I managed to implement it like this:
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetSecondaryRequest = function(callback, res) {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
var data = null;
http.get(OPTIONS, function(func, data) {
func.on('data', function(chunk) {
data += chunk;
});
func.on('end', function() {
callback(res, data);
});
}).on('error', function(e) {
callback(res, e);
})
};
var secReqCallback = function(res, recData)
{
res.write(recData);
res.end("END");
};
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
handleGetSecondaryRequest(secReqCallback, res);
} else {
res.writeHead(404);
}
};
server.listen(8000);
It works, kind of. There's an 'undefined' in front of the string which I can't find the cause for, but the basic functionality works perfect.
The callback construction is necessary to synchronize the asynchronous nature of NodeJS.
I do a http request in nodejs with the following code
var buffer = "";
var postToPHP = function(data, path){
var httpreq = require('http');
var querystring = require("querystring");
var data = querystring.stringify(data);
var options = {
host : 'localhost',
path : path,
method : 'POST',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : data.length
}
};
var buffer = "";
var reqPost = httpreq.request(options, function(res) {
res.on('data', function(d) {
buffer = buffer+d;
});
res.on('end', function() {
console.log("buffer",buffer); //this logs the buffer correctly
return buffer;
});
});
reqPost.write(data);
reqPost.end();
}
var buffer = postToPHP(message,path); //this buffer displays nothing because the call is async
I'd like to know exactly what is the standard procedure to "wait" for the server response in the nodejs or how to implement a callback that would react accordingly to what I want after I receive the message... Could someone give me an example of a callback on this please?
You have to pass in a callback if you're performing an asynchronous task inside a function:
var http = require('http'),
querystring = require('querystring');
function postToPHP(data, path, cb) {
var data = querystring.stringify(data);
var options = {
host: 'localhost',
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data.length)
}
};
http.request(options, function(res) {
var buffer = '',
calledBack = false;
res.on('data', function(d) {
buffer += d;
}).on('error', function(err) {
if (!calledBack) {
calledBack = true;
cb(err);
}
}).on('end', function() {
if (!calledBack) {
calledBack = true;
cb(null, buffer);
}
});
}).on('error', function(err) {
if (!calledBack) {
calledBack = true;
cb(err);
}
}).end(data)
}
Then use it:
postToPHP({ foo: 'bar' }, '/foo', function(err, data) {
if (err) throw err;
console.dir(data);
});