I have the following code. I am trying to get it to show the users in my db when I go to http://localhost:4000/user, however all I get is 404. I would appreciate some help as I'm clearly not understanding something.
app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var index = require('./routes/index');
var user = require('./routes/users');
var mongoose = require('mongoose');
var app = express();
//This is all setup code.
// view engine setup
app.set('view engine','ejs')
app.set('views', path.join(__dirname, 'views'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/user',user);
// 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
// render the error page
res.status(err.status || 500);
res.render('error');
});
//Mongo code
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db1')
.then(() => console.log('Connected to db succesfully'))
.catch((err) => console.error(err));
module.exports = app;
app.listen(4000, function () {
console.log('listening on port 4000!')
})
routes/user.js
var express = require('express');
var router = express.Router();
var userModel = require('../models/users.js');
/* GET home page. */
router.get('/user', function(req, res, next) {
console.log("get request made");
});
router.route('/user')
.get(function(req, res) {
User.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
.post(function(req, res) {
var user = new User(); // create a new instance of the Bear model
user.firstNamename = req.body.firstName; // set the bears name (comes from the request)
user.lastName=req.body.lastName;
user.email=req.body.email;
user.save(function(err) {
if (err)
res.send(err);
console.log("User created");
});
})
module.exports = router;
model/users.js
var mongoose = require('mongoose');
// Create a user schema
var userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
});
module.exports = mongoose.model('User', userSchema);
Three problems here:
first you've required ./routes/users but your route file is user.js, so it should be:
var user = require('./routes/user');
second, when you have mounted user middleware on your app you choose to prepend /user to all of user routes(app.use('/user', user);); so when you say:
router.route('/user').get(function ...
it responds to /user/user routes. so the right implementation is:
router.route('/').get(function ...
this responds to /user
third, semicolon before your post request should be removed.
Note that router.route('/').get(function... is exactly the same as router.get('/', function ... . we use first pattern for chaining different http verbs to one route. but semicolon destroyed the linking:
router
.route('/')
.get(function ...)
.post(function ...)
.delete(function ...);
Related
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.
I wanted to separate each group of routes in a file. I need to use isAuthenticated in most routes to restrict access. When I put all routes in the same file it works.
When I use module.exports = isAuthenticated in auth.js and in order.js I use var auth = require('auth.js'); I will get a error of 'isAuthenticated is not defined' when I go to http://localhost:3000/order the routes defined in auth.js just works as expected.
I'm using Express.js middleware 'Passport local strategy' (followed tutorial from tutsplus and downloaded github repository from here).
My project structure:
bin/www
models/auth/init.js
models/auth/user.js
models/auth/signup.js
models/auth/login.js
models/order.js
views/error.pug
views/index.pug
views/home.pug
views/layout.pug
views/order.pug
views/register.pug
routes/order.js
routes/auth.js
public/stylesheets/style.css
app.js
db.js
./routes/auth.js:
var express = require('express');
var router = express.Router();
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
module.exports = isAuthenticated;
module.exports = function(passport){
/* GET login page. */
router.get('/', function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
/* GET Home Page */
router.get('/home', isAuthenticated, function(req, res){
res.render('home', { user: req.user });
});
/* Handle Logout */
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
./routes/order.js:
var express = require('express');
var router = express.Router();
var order = require('../models/order');
var auth = require('./auth.js');
module.exports = function(passport){
router.get('/order', isAuthenticated, function(req, res){
res.render('order');
});
router.post('/order', isAuthenticated, function(req, res)
{
var testorder = new order({
orderid: '52363',
productname: 'it works',
quantity: 1337
});
testorder.save(function (err) {
if (err) {console.log(err.stack);}
console.log('saving done...');
});
res.render('order', { product: req.body.productname });
});
};
./app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var pug = require('pug');
var dbConfig = require('./db');
var mongoose = require('mongoose');
// Connect to DB
mongoose.connect(dbConfig.url);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize Passport
var initPassport = require('./models/auth/init.js');
initPassport(passport);
var auth = require('./routes/auth')(passport);
var order = require('./routes/order');
app.use('/', auth);
app.use('/order', order);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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
});
});
}
module.exports = app;
Try auth.isAuntheticated(),
It should work that way.
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);
});
});
I am currently implementing a server that handles PayPal API calls from client and comunicates with PayPal's services in order to get token and create users in braintree.
The deployment went out well regarding elastic beanstalk. When i call the token method through the router i get the token and a success. The problem stands when i try to create a new braintree customer i get a cryptic 502 error. Any idea why? I am using the standard nginx setup from AIM listening on port 80. This is not a duplicate since the other similar questions did not resolved my issue.
Using nginx 1.8.0
index.js
var express = require('express');
var router = express.Router();
var http = require('http');
var braintree = require('braintree');
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "xxxxxxxxxxxxxxx",
publicKey: "xxxxxxxxxxxxxxx",
privateKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
router.get('/', function(req,res) {
res.send('Iam a tree, a brain tree');
});
router.get('/token', function (req, res) {
gateway.clientToken.generate(null, function (error, response) {
res.json(response);
});
});
router.post('/createCustomer', function(req, res) {
var customer = req.body;
console.log(req.body);
gateway.customer.create({
firstName: customer.firstName,
lastName: customer.lastName,
company: customer.company,
email: customer.email,
phone: customer.phone,
fax: customer.fax,
website: customer.website
}, function (err, result) {
res.json(err,result);
});
});
module.exports = router;
main.js
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
And finally my www file
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../main.js');
app.set('port', process.env.PORT || 8081);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Answering my question since i found the issue of the problem. The root of the problem was in the "/createCustomer", removing err from
res.json(err,result);
and changing it to
res.json(result);
Also i am not creating a customer with options(name, last name) just an empty one. To wrap it up the "/createCustomer" router function looks like this now.
/* Get Creates a new customer with the given params */
router.post('/createCustomer', function(req, res) {
var customer = req.body;
console.log(req.body);
gateway.customer.create({}, function(err, result) {
res.json(result);
});
});
This is a bit strange since the first version of the function was copied from the Braintree documentation about Node server setup. Anyway for the moment this workaround allows to create a customer link it with my current user on a custom Parse server and edit its properties later.
I m learning from fast record on youtube. calls "Learn NodeJS building 10 projects". he is doing that at 15. video. Well this is my first post here. dont yell me cuz its my first message here. and please use easy english :) salute from turkey.
///THIS IS THE APP.JS
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = 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');
//handle file uploads multer
//app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// 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 }));
// handle express-session
app.use(session({
secret:'secret',
saveUninitialized: true,
resave:true
}));
// passport
app.use(passport.initialize());
app.use(passport.session());
// express-validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// connect-flash
app.use(flash());
// express-messages
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
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;
------------------------------
THIS IS THE USERS.JS
------------------------------
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/yenihesap', function(req, res, next) {
res.render('yenihesap',{
'title': 'Yeni Hesap Aç'
});
});
router.get('/giris', function(req, res, next) {
res.render('giris',{
'title': 'Giriş Yap'
});
});
router.get('/sifremiunuttum', function(req, res, next) {
res.render('sifremiunuttum',{
'title': 'Şifremi Unuttum'
});
});
router.post('/yenihesap', function(req, res, next){
// get form values
var name = req.body.name;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
// form validation
req.checkBody('name', 'Lütfen isminizi giriniz').notEmpty();
req.checkBody('lastname', 'Lütfen soyadınızı giriniz').notEmpty();
req.checkBody('email', 'Lütfen email adresinizi giriniz').notEmpty();
req.checkBody('email', 'Bu bir email adresi değil!').isEmail();
req.checkBody('password', 'Lütfen şifrenizi giriniz').notEmpty();
req.checkBody('password2', 'Şifreniz eşleşmiyor!').equals(req.body.password);
// check for errors
var errors = req.validationErrors();
if(errors){
res.render('yenihesap',{
errors: errors,
name: name,
lastname: lastname,
email: email,
password: password,
password2: password2
});
}else{
var newUser = new User({
name: name,
lastname: lastname,
email: email,
password: password
});
// create user
//User.createUser(newUser, function(err, user){
// if(err) throw err;
// console.log(user);
//});
//succes message
req.flash('success', 'Başarıyla kayıt oldunuz');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
this is the jade file
when even i full up to input forms correctly, all errors that i have. i dont understand why
I found the problem. Its about the multer. first of all it wasnt work with that code at the beggining
//handle file uploads multer
app.use(multer({dest:'./uploads'}));
the multer was giving me error and changed it to that
//handle file uploads multer
var upload = multer({ dest: './uploads' });
and this time multer had me this question problem that body parser wasnt work. so I changed to that. and it fixed my problem. I found it another question on stackover: typeerror: app.use() requires middleware function
//handle file uploads multer
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));
I m happy to joined this site. Its obviously perfect that people help each other. see you on next problems :)