node.js syntax error: SyntaxError: Unexpected end of input - node.js

I have an SyntaxError: Unexpected end of input. I'm new to Node. The error is on line 33 at }). I'm pretty sure it either has to do with the closing of a function but not quite sure.
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('/favorites', function(req, res){
var data = fs.readFileSync('./data.json');
res.setHeader('Content-Type', 'application/json');
res.send(data);
;
app.get('favorites', function(req, res){
if(!req.body.name || !req.body.oid){
res.send("Error");
return
var data = JSON.parse(fs.readFileSync('./data.json'));
data.push(req.body);
fs.writeFile('./data.json', JSON.stringify(data));
res.setHeader('Content-Type', 'application/json');
res.send(data);
};
app.list(3000, function(){
console.log("Listening on port 3000");
});

you forgot to close off the parenthesis for 2 get request
here:
app.get('/favorites', function(req, res){
var data = fs.readFileSync('./data.json');
res.setHeader('Content-Type', 'application/json');
res.send(data);
}); //here
and here:
app.get('favorites', function(req, res){
if(!req.body.name || !req.body.oid){
res.send("Error");
return
var data = JSON.parse(fs.readFileSync('./data.json'));
data.push(req.body);
fs.writeFile('./data.json', JSON.stringify(data));
res.setHeader('Content-Type', 'application/json');
res.send(data);
}); //here

Related

NodeSSPI 2 Minute Timeout on Post

When I send a request to my server I have no problem, but when I POST I run into a server timeout. (2 minutes by default, but if I add server.setTimeout(15000) I get a 15 second delay.) Once the server times out the process completes as expected. Interestingly, if I add a console.log(res) before the res.finished || next() the delay goes away.
post.html:
<form action="http://localhost:3000" method="post">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
test.js:
'use strict'
var express = require('express')
var app = express()
var server = require('http').createServer(app)
//server.setTimeout(15000);
const bodyParser = require("body-parser");
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi')
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
})
nodeSSPIObj.authenticate(req, res, function(err){
//console.log(res);
res.finished || next()
})
})
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/", function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<html>");
res.write("<body>");
res.write("<h1>My Header</h1>");
res.write("<p>My paragraph.</p>");
res.write("<p>Name = " + req.body.user.name + "</p>");
res.write("<p>Email = " + req.body.user.email + "</p>");
res.write("</body>");
res.write("</html>");
res.end();
console.log('End post');
});
// Start server
var port = process.env.PORT || 3000
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'))
})
It turns out the problem went away when I reordered the routing to put the bodyParser lines above the nodeSSPI check.
Specifically, I moved these lines:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
Above:
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi');
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: false
});
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next();
});
});

Express router not working

I'm new to express and used yo-generator to create my project. The problem I'm facing is that routes with:
app.get('/something') are working fine, but
router.get('/something') are not working. I tried to research but could not solve the problem.
Here are my files:
app.js
var fs = require('fs');
var http = require('http');
var path = require('path');
var helmet = require('helmet');
var express = require('express');
var root = path.normalize(__dirname + '/');
var constant = require(root + '/app/util/constants.js');
var config = require(constant.APP_CONFIG_FILE);
var app = express();
app.use(helmet());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
return next();
});
require('./config/express')(app, config);
http.createServer(app).listen(config.WEB_PORT, function() {
console.log('Server listening http on port ' + config.WEB_PORT);
});
module.exports = app;
Lines from express.js
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
app.set('views', config.ROOT + '/app/views');
app.set('view engine', 'ejs');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.ROOT + '/public'));
app.use(methodOverride());
var controllers = glob.sync(config.ROOT + '/app/controllers/*.js');
controllers.forEach(function(controller) {
require(controller)(app);
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app/controllers/user-ctrl.js
var path = require('path');
var express = require('express');
var router = express.Router();
var root = path.normalize(__dirname + '/../..');
var constant = require(root + '/app/util/constants.js');
var service = require(constant.USER_SERVICE_FILE);
var responseUtil = require(constant.RESPONSE_UTIL_FILE);
module.exports = function(app) {
app.use(constant.USER_PATH, router); // constant.USER_PATH is '/user' (added after alexmac asked)
**// this works**
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
**// This doesn't work**
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
};
/*
GET: /user
*/
router.route('/:page?/limit?/:limit')
.get(function(req, res) {
responseUtil.sendResponse(service.allRecords(req, res), req, res);
});
/*
POST: /user
*/
router.route('/')
.post(function(req, res) {
responseUtil.sendResponse(service.saveRecord(req, res), req, res);
});
/*
GET: /user/1
PUT: /user/1
DELETE: /user/1
*/
router.route('/:id')
.get(function(req, res) {
responseUtil.sendResponse(service.findRecord(req, res), req, res);
})
.delete(function(req, res) {
responseUtil.sendResponse(service.deleteRecord(req, res), req, res);
})
.put(function(req, res) {
responseUtil.sendResponse(service.updateRecord(req, res), req, res);
});
These are the key lines. I've changed the order to try to clarify the intent but that shouldn't change how they behave:
// Create a route for GET /test
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
// Create a route for GET /user/test
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/user', router);
The router is mounted at the path /user so any paths on the router will be relative to /user. In other words, if app is handling requests at http://localhost/test then router will handle http://localhost/user/test.
Change your code with this piece of code
var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
var app = express();
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/route',router);
module.exports = router;
When you want to get use http://localhost:port/route/test
Hope this helps.

Node.js post method is failing with 500 error

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.

Error connecting to mongolab using node.js and mongoose

I'm trying to write an API using mongoose and mongolab.
Here is my code :
./index.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:pass#****.mlab.com:*****/****');
var Bear = require('./app/models/bear');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function(req, res, next){
console.log('request called');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'in /' });
});
router.route('/bears')
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function(err) {
console.log('in save')
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);
and
./app/models/bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
My problem is, when I try the following request :
It doesn't return anything. I tried to console.log something in bear.save but in never goes in.
I don't get what I am doing wrong. Also when I try to connect to my mongolab db from my terminal it works perfectly well.
There's a problem with your index.js. Here, use this code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Bear = require('./bear');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function (req, res, next) {
console.log('request called');
next();
});
router.get('/', function (req, res) {
res.json({
message: 'in /'
});
});
/*router.route('/bears')*/
router.post('/bears', function (req, res) {
console.log("request: " + JSON.stringify(req.body));
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function (err) {
console.log('in save')
if (err)
res.send(err);
res.json({
message: 'Bear created!'
});
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);

How to link app.js to html page,so that I should display the progress bar in the browser using socket.io

I'm unable to link the index.html page to app.js.I'm trying to send the progress to index.html.But,I'm failing here.How can I overcome this issue?Can anyone please help me out ...
My index.html :
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
My app.js :
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
Updated 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 fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
// 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.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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: {}
});
});
module.exports = app;
You are not initializing Express properly so app is not hooked to any web server and thus app.get() isn't active.
Change this:
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
to this:
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
See the basic "Hello World" app example in the ExpressJS doc.
And, you will also need to make routes for jquery.js, bootstrap.js, etc... Remember, node.js doesn't serve any files by default. Since they are static files, you will probably want to use app.use(express.static(...)) to serve the static files.

Resources