how to send response in hhtp module - node.js

I'm new to node.js, So how to send duration in response in http module i tried sending it through req.write and req.writeHead(), but its not working.Help me with this issue
var https = require('https');
const config_KEYS = require('./config.js');
exports.handler = (event, context, callback) => {
var userLat = event.userLat;
var userLong = event.userLong;
var destinationLat = event.destinationLat;
var destinationLong = event.destinationLong;
var params = {
host:'maps.googleapis.com',
path: '/maps/api/distancematrix/json?units=imperial&origins='+userLat+","+userLong+'&destinations='+destinationLat+","+destinationLong+'&key='+config_KEYS.GOOGLE_API_KEY+'&departure_time=now'
};
var req = https.request(params, function(res) {
let data = '';
console.log('STATUS: ' + res.statusCode);
// res.setEncoding('utf8');
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
console.log("DONE");
const parsedData = JSON.parse(data);
console.log("data ===>>>>",parsedData);
var duration = parsedData.rows[0].elements[0].duration_in_traffic.text;
var obj = {}
obj.duration = duration
res.end(duration) ;
});
});
req.write(callback)
req.end();
};

In node js https there is one method like res.end() to send data after https request ends
Example:
const https = require('https');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample'
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
Here what you want to achieve is use function in res.on('end', ) and then return to that function. So, In your case it will not send in res.on('end', ) because untimately you're returning a value to function not a method.
Here is the solution:
const parsedData = JSON.parse(data);
console.log("data ===>>>>",parsedData);
var duration = parsedData.rows[0].elements[0].duration_in_traffic.text;
req.end('duration');
one more way is you can use callback. For the reference I am providing one link
Callback https

Related

check image resolution in hapijs

I am using hapi v17.1 .I am not an expert programmer. I need to get the resolution of an image in hapi js for server side image validation .
I have tried image-size plugin
var sizeOf = require('image-size');
var { promisify } = require('util');
var url = require('url');
var https = require('http');
................
// my code
................
const host = 'http://' + request.info.host + '/';
imageName = host + path;
try {
var options = url.parse(imageName);
https.get(options, function (response) {
var chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
var buffer = Buffer.concat(chunks);
console.log("image height and width = ",sizeOf(buffer));
});
});
} catch (err) {
console.log('error occured = ', err);
}
image-size plugin
for http it is working fine but I cant do it for https
when I tried for https url and showing the error
error occured = TypeError: https.get is not a function
at handler (/home/jeslin/projects/hapi/gg-admin/app/controllers/web/advertisement.js:178:31)
at <anonymous>
how can I implement this for https image url
For https request you should require https module require('https'), Sample snippet to handle http & https request for your reference.
var sizeOf = require('image-size');
var https = require('https');
var http = require('http');
var url = require('url');
const host = 'http://picsum.photos/200/300';
const request = (host.indexOf('https') > -1) ? https : http;
try {
request.get(host, function (response) {
var chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
var buffer = Buffer.concat(chunks);
console.log("image height and width = ",sizeOf(buffer));
});
});
} catch (err) {
console.log('error occured = ', err);
};

Why does NodeJs server return the same data 2 times?

I am currently learning NodeJs, thus I am building a simple NodeJs server which is called server.js
const http = require('http');
const port = 3000;
const fs = require('fs');
const sourceFile = './client/src/account.json';
var data = []
const service = http.createServer(
(req, res) => {
var receive = "";
var result = "";
req.on('data', (chunk)=>{ receive += chunk })
req.on('end', () =>{
data = fs.readFileSync(sourceFile, 'UTF8');
result = JSON.stringify(data);
var data_receive = receive;
console.log(data)
res.setHeader('Access-Control-Allow-Origin', '*');
res.write(data);
res.end()
})
})
service.listen(port)
Why does every time I request to the server, the console.log returns the data 2 times. It seems like it is looped somewhere.
This is my json file account.json
[
{
"id":"account_1",
"pass":"abc123",
"name":"Account 1"
}
]
Thank you for you help!
When performing the request from the browser, you will get an extra request for favicon.ico.
To avoid those double requests, handle the favicon.
if (req.url === '/favicon.ico') {
res.writeHead(200, { 'Content-Type': 'image/x-icon' });
console.log('favicon...');
return res.end();
}
/* The rest of your code */

How to download an ISO 8859-9 encoding XML file with node.js

for utf-8 encoded XML files there's no problem in using get method of http module. However when the encoding of the XML file is set to iso8859-9 , characters are not shown correctly. What could we do ?
var express = require('express');
var http = require('http');
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var router = express.Router();
getXml = function(resUrl, callback) {
http.get(resUrl, (res) => {
res.setEncoding('utf8');
let data = '';
// A chunk of data has been recieved.
res.on('data', (chunk) => {
data += chunk.toString();
});
// The whole response has been received. Print out the result.
res.on('end', () => {
callback(data);
});
}).end();
}
/* GET home page. */
router.get('/', function(req, res, next) {
getXml('http://server/xmlfile.xml', function(result) {
var doc = new dom().parseFromString(result);
var nodes = xpath.select("//person", doc);
let str = '';
nodes.forEach(element => {
str += element.attributes.getNamedItem("name").value + "<br/>";
});
res.render('index', {
title: 'Express' + str
});
});
});
module.exports = router;
Kind regards
var express = require('express');
var http = require('http');
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var router = express.Router();
getXml = function(resUrl, callback) {
http.get(resUrl, (res) => {
res.setEncoding('utf8');
let data = '';
// A chunk of data has been recieved.
res.on('data', (chunk) => {
data += chunk.toString();
});
// The whole response has been received. Print out the result.
res.on('end', () => {
callback(data);
});
}).end();
}
/* GET home page. */
router.get('/', function(req, res, next) {
getXml('http://server/xmlfile.xml', function(result) {
var doc = new dom().parseFromString(result);
var nodes = xpath.select("//person", doc);
let str = '';
nodes.forEach(element => {
str += element.attributes.getNamedItem("name").value + "<br/>";
});
res.render('index', {
title: 'Express' + str
});
});
});
module.exports = router;

Express nodejs router always on dealing

In my app.js, I definite a search router
app.use('/search', require('./router/search'))
In the search.js files, what I do is request a website and response website data, but the router always on dealing.
const express = require('express')
const router = express()
const url = require('url')
const http = require('http')
router.get('/', searchHandler)
function searchHandler(req, res) {
request('http://baidu.com', 'get')
.then(result => {
res.end(result)
})
}
function request(link, method, data) {
return new Promise((resolve, reject) => {
link = url.parse(link)
const result = '';
const options = {
hostname: link.hostname,
port: 80,
path: link.path,
method: method
}
http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
result += chunk;
});
res.on('end', function() {
resolve(result)
})
req.on('error', function(err) {
reject(err);
});
})
})
}
module.exports = router
why does my res.end(result) not works?

Node.js: Unable to compress response using express

I am using express version 4.13.4 and the following code for my app.js. I have tried changing the location of app.use(compression()) which did not show any effect. when I run the application I saw no evidence of compression in viewing the chrome dev tools response headers i.e it doesn't have the gzip content-encoding header.
I am new to node js.I want to gzip compress my response to browser. Please help me fix this issue.
var compression = require('compression')
var express = require('express');
var http = require('http');
var app = express();
app.use(compression());
var settings = {
UiServerPort: 8080,
ApiServerHost: "localhost",
ApiServerPort: 12121
};
app.use('/ui', express.static('ui'));
app.all('/api/*', function (req, res) {
var options = {
host: settings.ApiServerHost,
port: settings.ApiServerPort,
path: req.url.substring(4),
method: 'POST'
};
var requestData = '';
req.on('data', function (data) { requestData += data; });
req.on('end', function () {
var request = http.request(options, function (response) {
var responseData = '';
res.flush();
response.on('data', function (data) { responseData += data; });
response.on('end', function () {
res.statusCode = response.statusCode;
res.write(responseData);
res.end();
});
});
request.write(requestData);
request.end();
});
});
app.listen(settings.UiServerPort)
you saw " Vary Accept-Encoding " ?? if you don't use compression , this won't show. and I paste your code ,but It can't run.
Instead of
app.use(compression())
You should add this piece of code :
app.use(compression({filter: shouldCompress}))
function shouldCompress (req, res) {
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false
}
// fallback to standard filter function
return compression.filter(req, res)
}
PS : it works for me.

Resources