NodeJS error comes "can't find body parser" - node.js

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...');

Related

Why is DEBUG not logging in the console?

I am trying to take a tutorial on node.js and express. I'm trying to use the debug feature, but it is not logging anything to the console.
console.log works fine...but using debug() does not
I am on windows and am trying to run the app with...
set DEBUG=app ; node app.js
var express = require('express');
var chalk = require('chalk');
var debug = require('debug')('app');
var app = express();
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});
Try this:
var express = require('express');
var chalk = require('chalk');
var app = express();
var debug = require('debug')(app);
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});

POST route indicating 404 error (EXPRESS)

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);

db in db.collection.... is undefined, and I can't figure out why

Here is my server.js file. In my get '/' route, I keep getting db is not defined. I am trying to post retrieve documents from a mongodb collection, and eventually have the user be able to query the database using a document key:value. Any thoughts?
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds061355.mlab.com:61355/db');
app.use(bodyParser.urlencoded({extended: true}))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/:name', (req, res) => {
var cursor = db.collection('materials').find();
db.collection('materials').find().toArray(function(err, results) {
console.log(results);
});
});
app.listen(3000, () => {
console.log('Running app.js on 3000');
});
After the call to the connect method, you must use the connection property of the mongoose object. And you should also listen for events like error in case of an error and open to know when the connection is established successfully. You should proceed only once the connection is open. So your code should be something like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds061355.mlab.com:61355/db');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("Connected Successfully.");
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/:name', (req, res) => {
var cursor = db.collection('materials').find();
db.collection('materials').find().toArray(function(err, results) {
console.log(results);
});
});
app.listen(3000, () => {
console.log('Running app.js on 3000');
});
});

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);

Why is my express 4 middleware not being called?

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);

Resources