I'm using the following code to make GET request and to store the result in the local variable using node.js, the result stored in the variable is intended to send as sms. How do I compress the data stored in the result prior to sending it as sms? Please help
var express = require('express');
var request = require("request")
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello Cruel World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "my secret here";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
}
request("http://boilerpipe-web.appspot.com/extract?url=http: //"+content+"&extractor=LargestContentExtractor&output=text&extractImages=", function(error, response, data) {
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content:" " + data}
]
});
res.status(200).end();
});
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Assuming you want to compress the response to the browser, you will likely want to add a GZIP middleware package:
var compress = require('compression');
app.use(compress());
Related
The closest I've been able to get is it will have the client download them. It will download the correct ejs files.
It's driving me crazy because I feel like it should work but it will not. If I put html files in there they serve just fine. It's a little messy because I've been trying all sorts of things.
var application_root = __dirname;
var express = require('express');
var vhost = require( 'vhost' );
var https = require('https');
var http = require('http');
var fs = require('fs');
var path = require("path");
var forceSSL = require('express-force-ssl');
//do something
var app = express();
var credentials = {};
var config = require('./config.json')[process.env.NODE_ENV || 'dev'];
//Use ejs?
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
//Ensure all are going to www.
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
//Use the virtual hosts
app.use(vhost('*.seq.agency',express.static(path.join(__dirname + '/seq.agency'), {
extensions: ['ejs'],
index: 'index.ejs'
})));
app.get('/', function (req, res) {
res.send('vhosts didn\'t catch this!')
});
var httpServer = http.createServer(app);
if(config.name == "prod"){
/*var options = {
key: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/chain.pem')
}*/
console.log('starting on 443');
//var httpsServer = https.createServer(options, app);
//httpsServer.listen(443);
//httpServer.listen(80);
//app.use(forceSSL);
}
console.log('['+config.name+'] starting on port',config.port);
httpServer.listen(config.port);
The issue is that you are considering that static files are rendered. Static file as the name suggest is static and there is no dynamic behavior and template rendering needed for the same
That is why below code cannot work
app.use(vhost('*.seq.agency',express.static(path.join(__dirname + '/seq.agency'), {
extensions: ['ejs'],
index: 'index.ejs'
})));
As you are asking it to serve files as it is with no processing. So I modified your code a bit to show you an example how you could work something out on this
var application_root = __dirname;
var express = require('express');
var vhost = require( 'vhost' );
var https = require('https');
var http = require('http');
var fs = require('fs');
var path = require("path");
var forceSSL = require('express-force-ssl');
//do something
var app = express();
var credentials = {};
var config = require('./config.json')[process.env.NODE_ENV || 'dev'];
//Use ejs?
ejs = require("ejs");
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.engine('ejs', ejs.renderFile);
//Ensure all are going to www.
app.all(/.*/, function(req, res, next) {
var host = req.header("host");
if (host.match(/^www\..*/i)) {
next();
} else {
res.redirect(301, "http://www." + host);
}
});
//Use the virtual hosts
app.use(vhost('*.seq.agency',function (req, res, next)
{
const reqPath = req.path;
const paths =
[
reqPath + ".html",
reqPath + "index.html",
reqPath
]
for (file of paths) {
try {
let checkPath = path.join(__dirname,"seq.agency", file);
if (!fs.existsSync(checkPath))
continue;
let stat = fs.statSync(checkPath);
if (stat && stat.isFile())
{
res.render(checkPath);
return;
}
} finally {
}
}
console.log(file);
}));
app.get('/', function (req, res) {
res.send('vhosts didn\'t catch this!')
});
var httpServer = http.createServer(app);
if(config.name == "prod"){
/*var options = {
key: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/fullchain.pem'),
ca: fs.readFileSync('/etc/letsencrypt/live/kaleidoscope.wtf/chain.pem')
}*/
console.log('starting on 443');
//var httpsServer = https.createServer(options, app);
//httpsServer.listen(443);
//httpServer.listen(80);
//app.use(forceSSL);
}
console.log('['+config.name+'] starting on port',config.port);
httpServer.listen(config.port);
So the key is that we check a path in below order
reqPath + ".html",
reqPath + "index.html",
reqPath
And then if it exists then we render that in response. This is no way a production use code as it allows you to directory traversal attack, but this is to give you an idea of what you are doing wrong and how you should handle it
I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;
I am new to node.js. I am developing node js application using VS 2015. Below is my server code (app.js)
In one of routes (trains.js) I defined a simple post method like below. Thing is it is working fine from localhost. But once I deploy to azure websites, POST method is throwing Internal server error.
Can some one help me with this? Please let me know if you need any further details.
//Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var socketio = require('socket.io');
var global = require('./routes/globals.js');
GLOBAL._ = require('lodash');
GLOBAL.KEY = 'xxxxxxxxxxxxxxxxxxxxxx';
var availability = require('./routes/availability');
var fare = require('./routes/fare');
var stations = require('./routes/stations');
var pnr = require('./routes/pnr');
var route = require('./routes/route');
var trains = require('./routes/trains');
var app = express();
app.socket = socketio();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.set('port', process.env.PORT || 3000);
app.use('/availability', availability);
app.use('/fare', fare);
app.use('/stations', stations);
app.use('/pnr', pnr);
app.use('/route', route);
app.use('/trains', trains);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.socket.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
global.io = app.socket;
module.exports = app;
//Here is my train.js
var express = require('express');
var http = require('http');
var router = express.Router();
var utils = require("./utils.js");
var global = require('./globals.js');
router.get('/', function (req, res) {
var options = {
host: 'www.xxxxxxx.com',
path: '/test/xxxxxx/'
};
var parameters = {
fscode : 'xxxx',
tscode: 'xxxx',
//date: '',
//'class': '',
//orderby: '',
format: 'json',
pbapikey: '9xxxxxxxxa'
};
options.path += utils.getQueryString(parameters);
options.path += "pbapisign/" + utils.getHmacSHA1Signature(parameters);
callback = function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
res.send(data + "<h1>" + utils.hello() + "</h1>");
});
}
http.request(options, callback).on('error', function (error) {
console.log(error);
res.status(400).send(error.Message)
}).end();
});
router.post('/check', function (req, res) {
// console.log('Request -', req);
// console.log('Response -', res);
var data = {
request : "HELLO",
response: "VAMSI"
}
global.io.sockets.emit('NEW_CONTACT', data);
res.status(200).send('NEW DATA').end();
});
module.exports = router;
It seems that your code has not any obvious bug.
So if you can share some information for more detail, such as for error or deployment, I think it's helpful for investigating the issue.
Meanwhile, please try to install NTVS for your VS2015 and follow the wiki page Advanced Debugging - Remote Debugging on Windows Azure to debug your application.
I'm working on node js backend which receives user sms from android app using telerivet webhook API.everytime when i run the app atheroku it gives me cannot GET/ error ,my code for index.js is
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Our Backend Is Still in Alpha Stage,Hang Tight" }
]
});
}
res.status(200).end();
}
);
app.listen(process.env.PORT || 5000);
please help,where im i doing wrong
it gives me cannot GET/ error when i run the app on browser,and also doesnt reply for sms when testing with the app
I found the way out,this is my new code:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook', bodyParser.urlencoded({ extended: true }),function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Stay Tuned for Awesome " }
]
});
}
res.status(200).end();
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.
app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};
How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);