GET request response on to Jade page? - node.js

I've managed to make a GET request to an API however now I want to get the response on to a Jade page.
Here is my code for the GET request so far. This is in 'index.js' in the routes 'folder'. Any ideas about how I can get the response on to a Jade page?
router.get('/', function(req, res) {
var url = 'http://data.police.uk/api/forces';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body)
console.log("Successful")
});
}).on('error', function(e){
console.log("Error: ", e);
})
});
module.exports = router;

In your router
res.render('viewName',{"variable":"value"});
In your view
p #{variable}

Instead of trying to start from scratch, you should probably look at some sample templates for node.js with express.
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
This would tell you how to set up the structure of the app.

Related

Extracting POST request data from Express in Nodejs

I have a fairly simple express server that is designed to take external client data and publish it via mqtt to a gateway. It works perfectly with a hardcoded variable but I can't figure out how to extract the actual data from the POST request, which is as follows (it prints to the console just fine):
const postData = app.post('/send-data', function (req, res) {
console.log('connected', req.body);
res.status(200).json(req.body)
});
I need to get the req.body data out of that and into the following code that publishes the data to the topic:
client.on('connect', function () {
console.log('connected!');
client.publish('iot-2/type/wtlType/id/channel100/evt/event/fmt/json', publishData);
client.end();
});
publishData will just be the stringified json response.
This is the create server code if that helps:
https.createServer(options, app).listen(30002, () => {
console.log('Listening')
});
If I understand correctly your question is about the logic of getting the req.body published by the client. If so, then something like this should work:
let connected = false;
client.on('connect', function () {
console.log('connected!');
connected = true;
});
const postData = app.post('/send-data', function (req, res) {
console.log('connected', req.body);
res.status(200).json(req.body)
client.publish('iot-2/type/wtlType/id/channel100/evt/event/fmt/json', JSON.stringify(req.body));
client.end(); // are you sure you want this? can there not be more messages to broadcast?
});

Unexpected end of json input. File not able to parse completely

I have seen related questions on stack overflow as well as other websites and no solution worked out for me. I am working on a something which makes a get request. I am using expressjs and for get request i am using https module. The api from where I am making a get request is https://api.rootnet.in/covid19-in/stats/latest . I confirmed that it returns a json object. The code is:
const express = require('express');
const app = express();
const https = require('https');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
https.get(URL, function(response){
response.on('data', function(data){
console.log(JSON.parse(data));
});
});
});
app.listen(3000, function(){
console.log("server started");
});
the output i am getting is:
server started
undefined:1
{"success":true,"data":{"summary":{"total":343091,"confirmedCasesIndian":335359,"confirmedCasesForeign":48,"discharged":180013,"deaths":9900,"confirmedButLocationUnidentified":7684},"unofficial-summary":[{"source":"covid19india.org","total":344015,"recovered":180331,"deaths":9920,"active":153721}],"regional":[{"confirmedCasesIndian":41,"confirmedCasesForeign":0,"discharged":33,"deaths":0,"loc":"Andaman and Nicobar Islands","totalConfirmed":41},{"confirmedCasesIndian":6456,"confirmedCasesForeign":0,"discharged":3316,"deaths":88,"loc":"Andhra Pradesh","totalConfirmed":6456},{"confirmedCasesIndian":91,"confirmedCasesForeign":0,"discharged":7,"deaths":0,"loc":"Arunac
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (C:\Users\sasmit\Desktop\covid 19\testapp.js:15:24)
at IncomingMessage.emit (events.js:315:20)
at IncomingMessage.Readable.read (_stream_readable.js:506:10)
at flow (_stream_readable.js:1006:34)
at resume_ (_stream_readable.js:987:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
seems like it is not able to parse the entire file.
It's because the response is sent in chunks. After each chunk the data event is emitted. But it doesn't mean the response is fully sent. To make sure the reponse is complete, you need to use end event and parse the reponse then:
const URL = 'https://api.rootnet.in/covid19-in/stats/latest';
let result = '';
https.get(URL, function(response){
response.on('data', function(data){
result += data;
});
response.on('end', function() {
console.log(JSON.parse(result));
});
});
When you try to parse it as JSON it is converted to a string, which is empty, So, you can give this a try
app.get('/', function(req, res){
var URL = 'https://api.rootnet.in/covid19-in/stats/latest';
https.get(URL, function(res){
var json = '';
res.on('data', function(data){
json += data;
});
res.on('end', function(){
var response = JSON.parse(json);
console.log(" JSON Parserd ", response.success);
});
}).on('error', function(e){
console.log("Error occured while parsing ", e);
});
});

Want to write capture and re-transmit http/https request to Browser?

I want to write a simple Node Js application which will capture and re-transmit http/https request to Browser?
I have written the below code, but it works only for http request.
var server = http.createServer(function (req,res) {
console.log("start request:", req.url);
var option = url.parse(req.url);
option.headers = req.headers;
var proxyrequest = http.request(option, function (proxyresponce) {
proxyresponce.on('data', function (chunk) {
console.log("proxy responce length" ,chunk.length);
res.write(chunk,'binary');
});
proxyresponce.on('end',function () {
console.log("proxy responce ended");
res.end();
});
res.writeHead(proxyresponce.statusCode, proxyresponce.headers);
});
});

Post an xml File to nodjs server?

i am having an xml file.I need to expose an api in such a way that it can consume xml files throughnodjs server api.
how can i receive a simple xml file in my nodejs server. i need a nodejs server script.
Try this code after struggling sometime I successfully get the code as per your need.
var express = require('express');
var fs=require('fs');
var app = express();
var conf;
var result;
app.get('/Excel', function(req, res){
result=fs.readFileSync('E:/User/nodejs/nodejs/tasks/result.xml');
res.end(result);
});
app.post('/posting',function(req,res){
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.writeFile('E:/User/nodejs/nodejs/tasks/result.xml', body, function() {
console.log(body);
res.end('Successfully Posted');
});
});
});
app.listen(3000);
console.log('Listening on port 3000');
After you run the server Post the data in content-type as application/xml using http://localhost:3000/posting and place your code in body and as result result.xml file will be created with the data.And you can get this file by http://localhost:3000/Excel.Hope this helps for you.
You can use a simple XML parser middleware such as express-xml-bodyparser. A working examples with express can be found in the above mentioned site.

node.js - end the request immediately?

So I have the following code -
var http = require('http');
http.createServer(function (req, res) {
console.log("Connected!");
res.writeHead(200);
req.on('data', function(data) {
res.write(data);
});
}).listen(5000);
But when I write into chrome localhost:5000 it just load the page, and then it says that the server didn't sent any data..
I figured out that If I write req.end(); after the data event, it loads the page perfectly. However, I don't want to end the request immediately.
What should I do?
You'll have to call res.end() at some point, but you can wait for the req to 'end' first:
req.on('end', function () {
res.end();
});

Resources