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);
Related
I'm currently working on a register and login system with Express, Node, Mongoose and Passport.js and the register mostly works fine , but there's a big issue with the login system. For some reason in the method I've created passport cannot read "passport" of undefined, so something is coming up as undefined but I can't seem to figure it out.
I don't know why it's not working, any help please!!
this my code
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
users.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
router.post('/register', (req, res, next) =>{
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to register user'});
}else {
res.json({success: true , msg:'User registered'});
}
});
});
router.post('/authenticate', (req, res, next) =>{
res.send('AUTHENTICATE');
});
router.get('/profile', (req, res, next) =>{
res.send('PROFILE');
});
module.exports = router;
Your issue is with passport session. You need to use express session (remember to install in your dependencies) before it for it to work properly.
Your app.js should look like this:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const session = require("express-session");
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(session({secret: "secret"});
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
Also, keep in mind that body parser is deprecated for Express 4.16.0 or higher. It has been re-added in methods express.json() and express.urlencoded() so if your Express version falls into that category, you can change your app.js to:
const express = require('express');
const path = require('path');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const session = require("express-session");
mongoose.connect(config.database);
mongoose.connection.on('connected', () => {
console.log('Connected to database ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('Database error:' + err);
});
const app = express();
const users = require('./routes/users');
const port = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({secret: "secret"});
app.use(passport.initialize());
app.use(passport.session());
app.use('/users', users);
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
app.listen(port, () =>{
console.log('Server started on port' + port);
});
I suggest adding comments to your code to keep it neat as well.
In case anyone else runs into this error:
express-session deprecated undefined resave option; provide resave option
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option app.
In addition to #raijin30 answer, I had to add the properties below (:
resave: true,
saveUninitialized: true
Explanation as to why, can be found at: Node JS session error: express-session deprecated.
Had the same problem and noticed that passport got updated on Septmeber 23rd. So, I decided to install the previous version via npm using
npm install --save passport#0.4.1
This solved the issue for me. Not really sure how or why it happened in the first place, but it might help you.
When I try to run the NodeJs code using nodemon command. The error says that can't find body-parser.But I included the body-parser requirement in the app.js . But the same error comes over and over again
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
trainInfo = require('./models/trainInfo');
mongoose.connect('mongodb://localhost/traindb');
var db = mongoose.connection;
app.get('/', function(req, res) {
res.send('Hello world');
});
app.get('/api/trainInfo', function (req, res) {
trainInfo.getTrainInfo(function (err, trainInfo) {
if(err){
throw err;
}
res.json(trainInfo);
});
});
app.listen(3000);
console.log('Running on port 3000...');
Getting a 404 error on my POST route, here is what I have done in my auth.js (routes) file:
const express = require('express');
const router = express.Router();
const connection = require('../../helpers/db.js');
const bodyParser = require("body-parser");
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({
extended: true
}));
//create a new user
router.post('/signup', function (req, res) {
const insert = `INSERT INTO users ( email, password, name, lastname) values ('${req.body.email}', '${req.body.password}','${req.body.name}', '${req.body.lastname}' )`
connection.query(insert, function (err, result) {
if(err) {
console.log('mysql error', error);
res.status(500);
res.send(error);
} else {
console.log('a new user was added!');
res.send('Congrats, new user!');
}
})
});
module.exports = router;
Here is my app.js file:
const http = require("http");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const app = express();
const authRouter = require("./routes/auth/auth");
// Configuring the app
app.use(morgan("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.use("/signup", authRouter);
//starting node server
const server = app.listen(process.env.PORT || 3001, function(err) {
if(err) throw err;
console.log("Listening on port " + server.address().port);
});
If I change my route into a GET, it works fine, but as soon as I do a POST route it would keep telling me on postman there is a 404 error, been trying many things but im now stuck! Im a beginner here :)
I think you added a prefix to your route so the route is /signup/signup
Try to change this
app.use("/signup", authRouter);
To this
app.use(authRouter);
When I did res.json (newschema) on post action, the properties are not displayed any more on Postman and also in Mongodb.
This is formations.routes
const express = require('express');
const router = express.Router();
const Formation = require('../models/formations');
const mongoose = require('mongoose');
const config = require('../config/database');
router.get('/', function(req, res){
//Formation.getFormations(function(err, formations){
// if(err)throw err;
// res.json(formations);
//});
Formation.find({})
.exec(function(err, Formations){
if(err){
console.log('error');
}else{
res.json(Formations);
}
})
});
router.post('/', function(req, res){
console.log('post a formations');
var newFormation = new Formation();
newFormation.title = req.body.title;
newFormation.url = req.body.url;
newFormation.description = req.body.description;
newFormation.save(function(err, newFormation){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
});
This is formation.models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const config = require('../config/database');
const FormationSchema = mongoose.Schema ({
title: String,
url: String,
description: String
});
module.exports = mongoose.model('Formation', FormationSchema, 'Formations');
This is my app.js ( endpoint)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const User = require('./models/user');
const Formation = require('./models/formations');
mongoose.connect(config.database , { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('connected to database... ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('database error'+err);
});
/*mongoose.connect('mongodb://localhost:27017/hello', { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected!');
});*/
const app = express();
const users = require('./routes/users');
const formations = require('./routes/formations');
//port number
const port = 3001;
//cors middleware
app.use(cors({
origin: 'http://localhost:4200'
}));
//passwport middelware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport); //pour implémenter fichier passport.js
//set static folder
app.use(express.static(path.join(__dirname + '/public')));
//BodyParser middleware
app.use(express.json());
app.use(bodyParser.json());
app.use('/users', users);//hedhiya ki nekteb /users barka f url yemchili direct lel const users = require('./routes/users'); fichier hedhka
app.use('/formations', formations);
//c un route
//just meloul 7atineha bch ntastiw beha
//index route
app.get('/', function(req, res){
res.send('invalid endpoint');
});
//start Server
app.use(bodyParser.urlencoded({extended:true}));
app.listen(port, () => {
console.log('Server started on port' +port);
});
And this is how I make a post action in Postman
The save method only has an error parameter in the callback. You are adding a newFormations parameter which will always be undefined and in the scope of the method you are returning undefined in the res.json call. To fix it remove the newFormation parameter as below:
newFormation.save(function(err){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
I have the following Express 4 code:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var log = require('npmlog');
var httpStatus = require('http-status-codes');
var config = require('./config');
var routes = require('./routes');
app.use(function (err, req, res, next) {
log.verbose('Express', '%s %s', req.method, req.url); //Never called
next();
});
app.use(function (err, req, res, next) {
if(err) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).send(err.message); //Never called
}
});
app.use(bodyParser.json());
app.use('/api', routes);
mongoose.connect(config.mongoAddress,
{keepAlive: 1, server: {auto_reconnect: true}},
function (err) {
if (err) {
log.error('Mongo', 'Could not connect to mongo database');
throw err;
} else {
log.info('Mongo', 'Successfully established connection to ' + config.mongoAddress);
}
}
);
var server = app.listen(config.port, function () {
log.info('Server', 'Server listening at %s', server.address().port);
});
My route is working fine, however both functions I have before app.use(bodyParser.json()); are never being called (I also tried adding breakpoints, to no avail). I also tried putting those functions AFTER the route is added, which didn't help (but that was expected).
What am I forgetting?
What's happening is this:
You're including your routes BEFORE you define your middleware. What you should be doing is something like this:
var app = express();
// setup all middlewares here
app.use(...);
app.use(...);
// include all routes here
app.use(routera);
app.use(routerb);