Express nodejs router always on dealing - node.js

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?

Related

express.js form post req.body is empty body {}

I have the following reactjs code and using expressjs to handle the post request. req.body always returns {} from the app. But it works in Postman.
my reactjs code snippet:
handleSubmit(e) {
e.preventDefault();
fetch(config.urlDev + '/notes', {
method: 'post',
body: { "email":"test" },
//headers: {'Content-Type':'x-www-form-urlencoded'}
headers: {'Content-Type':'application/json'}
})
.then((res) => res.json())
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
})
}
my expressjs code snippet:
module.exports = function (app, db) {
app.post('/notes', (req, res) => {
console.log(req.body)
console.log(req.params)
res.send(req.body)
})
}
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient
const bodyParser = require('body-parser')
const db = require('./config/db');
const app = express();
const port = 8000;
const cors = require('cors');
const path = require('path');
app.use(cors())
//app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
MongoClient.connect(db.url, {useUnifiedTopology: true}, (err, database) => {
if (err) return console.log(err)
const mydb = database.db('notes')
require('./app/routes') (app, mydb);
app.listen(port, () => {
console.log ("server on " + port)
})
})
postman
Try un-commenting the line
//app.use(bodyParser.json()) and it should work.
or alternatively if you are sending headers in the fetch request as headers: {'Content-Type':'x-www-form-urlencoded'} instead of headers: {'Content-Type':'application/json'} it should work.

How can I maintain persist a Cloud Functions connection using ExpressJS

const http = require('http');
const functions = require('firebase-functions');
const agent = new http.Agent({keepAlive: true});
exports.function = functions.https.onRequest((request, response) => {
req = http.request({
host: '',
port: 80,
path: '',
method: 'GET',
agent: agent,
}, res => {
let rawData = '';
res.setEncoding('utf8');
res.on('data', chunk => { rawData += chunk; });
res.on('end', () => {
response.status(200).send(`Data: ${rawData}`);
});
});
req.on('error', e => {
response.status(500).send(`Error: ${e.message}`);
});
req.end();
});
This is the code from Optimizing networking using Cloud Functions. How can I update it to use expressJS.
So from the code I see that the trick is this line const agent = new http.Agent({keepAlive: true}) and then in the request agent: agent.
I tried doing something like
const server = express()
server.use((req, res, next) => {
req.agent = new http.Agent({keepAlive: true})
next()
})
But did't work. HELP!!!
Just put on index.js
require('https').globalAgent.keepAlive = true;

How do I GET a png image through nodejs express app making a call to an API

I need to be able to return a png image from and API endpoint through nodejs express app.
When trying to return an image/svg file, it returns and renders as expected. But when |I try with a png file, I get some poorly encoded text like so:
�PNG IHDR\���IDATx�]�U��:Ӂ�.��*��������]�{�A�A�(�� �\���1��� �� A#6���$�(�CXX|d��IUu�dz�渤�g��u�����sO�1��g��W�����~fv��+�TL�z�qןc��e��;��{��狿
Here is the code I have now:
const express = require('express')
const request = require('request-promise')
const port = 3000
const exphbs = require('express-handlebars')
const app = express()
const options = {
method: 'GET',
uri: 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
headers: {
'Accept': 'image/png',
'Content-Type': 'image/png'
}
}
app.get('/', (request, response) => {
test(response)
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
function test(resp){
return request(options).then((data)=>{
resp.header('Content-Type', options.headers['Content-Type']).send(data);
}).catch((err) => {
console.log(err)
data.render('error')
})
}
Solution to my problem here. Thanks to #LawrenceCherone
const express = require('express')
const request = require('request-promise')
const port = 3000
const exphbs = require('express-handlebars')
const app = express()
const options = {
method: 'GET',
uri: 'https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png',
headers: {
'Accept': 'image/png'
}
}
app.get('/', (request, response) => {
response.setHeader('Content-Type', 'image/png')
makeRequest(response)
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
function makeRequest(resp){
request(options.uri, options).pipe(resp)
}

How to subscribe a HTTP endpoint to SNS in node js?

I am trying to subscribe my endpoint to a topic (I am using an EC2 instance), I have tried visiting my endpoint in a browser (GET request) to call sns.subscribe but I am not receiving a POST request afterwards.
The response I get from calling sns.subscribe is this.
{ ResponseMetadata: { RequestId: 'xxxx-xxxx-xxxx-xxx-xxxx' },
SubscriptionArn: 'arn:aws:sns:topic_location:xxxx:topic_name:xxxx-xxxx-xxxx-xxx-xxxx' }
This is my code.
const express = require("express");
const AWS = require('aws-sdk');
const request = require('request')
const bodyParser = require('body-parser')
const app = express();
var SNS_TOPIC_ARN = "arn:aws:sns:topic_location:xxxx:topic_name";
// configure AWS
AWS.config.update({
'accessKeyId': 'mykey',
'secretAccessKey': 'mysecretkey',
"region":"myregion"
});
const sns = new AWS.SNS();
app.get('/', (req, res) => {
var params = {
Protocol: 'http', /* required */ //http , https ,application
TopicArn: SNS_TOPIC_ARN, /* required */ // topic you want to subscribe
Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/:80', // the endpoint that you want to receive notifications.
ReturnSubscriptionArn: true //|| false
};
sns.subscribe(params, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
res.end();
});
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post('/', (req, res) => {
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let payload = JSON.parse(body)
if (payload.Type === 'SubscriptionConfirmation') {
const promise = new Promise((resolve, reject) => {
const url = payload.SubscribeURL
request(url, (error, response) => {
if (!error && response.statusCode == 200) {
console.log('Yess! We have accepted the confirmation from AWS')
return resolve()
} else {
return reject()
}
})
})
promise.then(() => {
res.end("ok")
})
}
})
})
app.listen(80, process.env.IP, function(request, response){
console.log("## SERVER STARTED ##");
});
I had to remove my port number from the endpoint when calling sns.subscribe! My subscription has now been confirmed :D The new endpoint looks like this.
Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/

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;

Resources