SyntaxError: Unexpected token ) - node.js

I am using Cassandra + Node.js to create an app, but I am receiving an error for this code:
C:\Users\userx\node-cassandra\app.js:44
app.post('/',new);
^
SyntaxError: Unexpected token )
at Module._compile (module.js:545:28)
This is my code
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 helenus = require('helenus');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var pool = new helenus.ConnectionPool({
hosts : ['localhost:9160'],
keyspace : 'webinar',
cqlVersion : '3.0.0',
//user : 'test',
//password : 'test1233',
//timeout : 3000
//cqlVersion : '3.0.0' // specify this if you're using Cassandra 1.1 and want to use CQL 3
});
pool.connect(function(err){
if(err){
throw(err);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('cassandra',pool);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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.get('/', routes.index);
app.post('/', new);
app.delete('/', delete);;
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
});
index.js
exports.index = function(req, res, next){
req.app.get('cassandra').cql('SELECT * FROM users LIMIT 10',function(err, users){
if(err){
return next(err);
}
res.render('index', { title: 'Users', users: users });
});
};
exports.new = function(req, res, next){
var insert = 'UPDATE users SET first_name=?, last_name=? WHERE email=?',
params = [req.body.first_name, req.body.last_name, req.body.email];
req.app.get('cassandra').cql(insert, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
exports.delete = function(req, res, next){
var remove = 'DELETE FROM users WHERE email=?',
params = [req.body.email];
req.app.get('cassandra').cql(remove, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
Error
SyntaxError: Unexpected token )
i just tried to change the app.post('/',routes.new);
but it showed inheritance mustnot be done
Please tell me where is my mistake

new is a reserved word in ECMAScript. I don't think you will be able to use it as a member name as it is being interpreted as creating a new object.

Related

How can i get values of parameters using postman?

I am working on Node JS and PostgreSQL and I am creating REST web service using this. I have created a post method and calling web service through POSTMAN but unable to get parameter values in my function. Web service inserting null value in my PostgreSQL table. I am using Visual studio 2015 unable to debug code. How can I achieve this ?
queries.js
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://test:12345#localhost:8080/test';
var db = pgp(connectionString);
function getAllTask(req, res, next) {
debugger;
db.any('select * from tasklist')
.then(function (data) {
res.status(200)
.json({
status: 'success',
message: 'Retrieved ALL puppies',
data: data
});
})
.catch(function (err) {
return next(err);
});
}
function addTask(req, res, next) {
debugger;
//var task_name = req.param('task_name');
//var task_type = req.param('task_type');
var task_name = req.body.task_name;
var task_type = req.body.task_type;
console.log(req.body);
db.func('inserttask', [task_name, task_type])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one task'
});
})
.catch(function (err) {
return next(err);
});
}
module.exports = {
getAllTask: getAllTask,
addTask: addTask
};
index.js
var express = require('express');
var router = express.Router();
var db = require('../queries');
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/tasklist', db.getAllTask);
router.post('/api/addtask', db.addTask);
module.exports = router;
server.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 index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon iblic
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am assuming that you are already using express js as framework for node js.
First of all you need to install body-parser module from npm:-
$ npm install body-parser --save
Once you have installed body-parser, add following code once after you have defined app variable:-
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // to support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support encoded bodies
Now you can access your post request body paramters as req.body.task_name and req.body.task_type
Hope it works and I am sorry if I have misunderstood your question.
You need to add Content-Type: application/json inside Headers when you send request through POSTMAN.

Express.js request.body not working

I have a simple form for login, the problem is when i press "Submit", the request.body on server side is empty.I saw that bodyParser is a fundamental part but in my case it's declared before the routes, so i think the problem is another. this is my server page App.js
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// 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(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000);
module.exports = app;
this is index.js
var express = require('express');
var router = express.Router();
function Login(req, res){
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect('mongodb://localhost:27017/squaredDB', function(err, db) {
if(err) throw err;
db.collection('users').find({email: req.body.email}, function(err, data){
console.log(req.body);
});
});
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
Login(req, res);
res.render('app-home', { title: '' });
});
module.exports = router;
this is my jade template form:
form(method="post" action="/")
label Email
input(type="text" placeholder="Email")
label Password
input(type="password" placeholder="Password")
input(type="submit" value="login")
You're missing name attributes for your input fields in your template. Without those the browser won't submit them in the form.
Add a name attribute to your input field it will now be able to access the field via request like req.body.name
<form action="/", method="POST">
<input type="text" placeholder="name" name="name">
<button type="submit">Submit</button>
</form>

HTTP post request parameters doesn't change default values of Mongoose schema

I created two Mongoose schemas and want to test them with Postman.
When I send a post HTTP request my parameters doesn't change the default value from the AnimalSchema nor does at StorySchema.
var mongoose = require('mongoose');
var AnimalSchema = new mongoose.Schema({
name: {type : String, default: ""},
audio: {type : String, default: ""},
image: {type : String, default: ""}
});
mongoose.model('Animal', AnimalSchema);
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Animal = mongoose.model('Animal');
var Story = mongoose.model('Story');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/animals', function(req, res, next){
Animal.find(function(err, animals){
if(err){
return next(err);
}
res.json(animals);
});
});
router.post('/animals', function(req, res, next){
var animal = new Animal(req.body);
animal.save(function(err,animal){
if(err){return next(err);}
res.json(animal);
});
});
router.get('/stories', function(req, res, next){
Story.find(function(err, stories){
if(err){return next(err);}
res.json(stories);
});
});
router.post('/stories', function(req, res, next){
var story = new Story(req.body);
story.save(function(err, story){
if(err){return next(err);}
res.json(story)
});
});
module.exports = router;
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 app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/stuckyToys', function(err,db){
if (!err){
console.log('Connected to /stuckyToys!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Animals');
require('./models/Stories');
var routes = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I think I made an error in my app.js file. But not sure where it is.
Anyone knows what I did wrong?
I would do something like
{*(Model)}.findById(id, function(err, animal) {
if (err) console.log(err);
{update new values here in animal with the ones you are receiving in the request}
animal.save(function(err) {
if (err) console.log(err);
});
});

How to share Session across multiple route JS files in ExpressJS

First of all, I am using:
express-session#1.14.2
express#4.14.0
I am basically trying to get a login system working and when user logs in, I set session.isloggedin = true.
So this 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 session = require('express-session');
var index = require('./routes/index');
var portfolioRoute = require('./routes/portfolio');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true,
maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.use('/', index);
app.use('/portfolio', portfolioRoute);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The index.html contains the login form.
Next, my index.js
var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');
var sess;
/* GET home page. */
router.get('/', function (req, res) {
sess = req.session;
console.log("SESSION IS: " + sess.isLoggedIn);
if(sess.isLoggedIn) {
res.render('portfolio', { isLoggedIn: true })
} else {
res.render('index', { isLoggedIn: false })
}
})
//END ------------
if(global.GLB_PORTFOLIO === null) {
port.getPortfolio(null, function(err, result) {
global.GLB_PORTFOLIO = result;
});
}
// API Routes
//router.use('/api', router);
router.route('/api/login')
.post(api.postLogin)
router.route('/api/portfolio')
.post(api.postPortfolio)
.get(api.getPortfolio)
//END ------------
module.exports = router;
Next, my api.js:
var util = require('util');
const backend = require('./portfolio.js');
exports.postPortfolio = function(req,res) {
backend.insertPortFolio(req.body, function(err, result) {
res.json({ result: result, error:err });
});
}
exports.getPortfolio = function(req,res) {
backend.getPortfolio(req, function(err, result) {
global.GLB_PORTFOLIO = result;
res.json({ portfolio: result, error: err });
});
}
exports.postLogin = function(req,res) {
backend.findUserByEmail(req.body.email, function(err, result) {
console.log("API: SESSION IS: " + req.session.isLoggedIn);
if(err || result === null) {
req.session.isLoggedIn = false;
} else {
req.session.isLoggedIn = true;
}
req.session.save();
res.json({ user: result, error: err });
});
}
The session variable is always undefined even after the save(). What am I doing wrong?

node/express session to pass an object to the view

I have this post login that stores an object in req.locals.user.
var router = express.Router();
var User = require('../models/user');
var Company = require('../models/company');
/* GET home page. */
router.get('/', function(req, res) {
res.render('users/login');
});
router.post('/users/login', function(req, res){
var email = req.body.email;
var password = req.body.password;
User.find({email: email, password: password}, function(err, user){
if(user.length == 0)
{
//user wasn't found
res.render('users/login', {validation: "Invalid Email Or Password"})
}
else
{
//user was found set session and local objects
req.session.user = user;
res.locals.user = user;
res.redirect('/dashboard');
}
});
});
my problem is that when I redirect the user to the dashboard. I get an error message saying that my object is undefined.
<h1 class="page-header">Dashboard v2 <small><%=user.firstName%>.</small></h1>
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 mongoose = require('mongoose');
var moment = require('moment');
var session = require('express-session');
var dashboard = require('./routes/dashboard');
var users = require('./routes/users');
var categories = require('./routes/categories');
var products = require('./routes/products');
var sales = require('./routes/sales');
var companies = require('./routes/companies');
var app = express();
// set locals
app.locals.moment = moment;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__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(session({resave: true, saveUninitialized: true, secret:"mySecretString"}));
app.use(function(req,res,next){
res.locals.user = req.session.user;
delete req.session.user;
next();
}
app.use('/', dashboard);
app.use('/', users);
app.use('/', categories);
app.use('/', products);
app.use('/', sales);
app.use('/', companies);
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "api_key");
if(req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});
// 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
});
});
mongoose.connect('mongodb://localhost/test');
}
// 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;
How do I pass my object globally between my views ?
Problem because res.locals.user will be remove when you redirect (next request). Only req.session exists.
For set variable to next request. You need a middleware to set session to locals again
app.use(function(req,res,next){
res.locals.user = req.session.user;
delete req.session.user;
next();
});

Resources