Body parsing isn't passing any data when i use postman to make a request. When i use the console.log to view the req.body it gives an empty object.. Any ideas why this is happening
Thanks
const app = require('express')();
const morgan = require('morgan');
const mongoose = require('mongoose');
const User = require('./models/user');
const bodyParser = require('body-parser');
const uri = 'mongodb://localhost:27017/amazon';
mongoose.connect(uri, function(err) {
if (err) throw err;
console.log('Connected to the DB');
})
const port = process.env.PORT || 3000;
// Middlewares
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.json('Hellow');
});
app.post('/create-user', function(req, res, next) {
console.log(req.body);
let user = new User();
user.profile.name = req.body.name;
user.password = req.body.password;
user.email = req.body.email;
user.save(function(err) {
if (err) return next(err);
res.json('Successfully created user ' + user.profile.name);
})
})
app.listen(port, function(err) {
if (err) throw err
console.log('Server running');
});
Postman request should look similar to this image attached
Adding Content-Type : "application/x-www-form-urlencoded" should resolve ur issue.
Related
I am new to Node.js and trying to create a login and signup API's and storing these data in MongoDB, but when I post the signup request I get error Socket Hangup (Could not get Response). I have tried a lot but didn't able to debug why I am getting this problem.
Here is my app.js code
'use strict'
var createError = require('http-errors');
var express = require('express');
var path = require('path');
const fs=require('fs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose=require('mongoose');
const Dishes=require('./Model/schema');
const session=require('express-session');//used for creating the session
const FileStore=require('session-file-store')(session);//used to create the file for the storage of cookies
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
//var promoRouter = require('./routes/promoRouter');
//var leaderRouter = require('./routes/leaderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Sauravpandey:85ffxufexfEP3HXzPPq#saurav-5irg5.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true,useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
console.log('conected properly to drive');
// perform actions on the collection object
client.close();
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
name:'session-id',
secret:'12345-67890-09876-54321',
saveUninitialized:false,
resave:false,
store:new FileStore()
}))
app.use('/', indexRouter);
app.use('/users', usersRouter);
//app.use(cookieParser('12345-67890-09876-54321'));
///////////////////----------------authorization process-----------------------////////////////////
function auth (req, res, next) {
console.log(req.session);
if(!req.session.user){
var err = new Error('You are not authenticated!');
err.status=403;
return next(err);
}
else{
if(req.session.user==='authenticated'){
next();
}
else{
var err = new Error('You are not authenticated!');
err.status = 403;
return next(err);
}
}
}
app.use(auth);
app.use(express.static(path.join(__dirname, 'public')));
// modifications done
app.use('/dishes',dishRouter);
// catch 404 and forward to error handler
app.all('/',(req,res,next)=>{
res.statusCode=200;
res.setHeader('Content-Type','text/plain');
next();
});
app.listen(3000,()=>console.log("Server is started listening at port 3000"));
Here is user.js file-
var router = express.Router();
var mongoose=require('mongoose');
var User=require('../Model/user');
var bodyParser=require('body-parser');
router.use(bodyParser.json());
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
//------------------------------------- SignUp-----------------------///////////////////
router.post('/signup',(req,res,next)=>{
User.findOne({username:req.body.username})
.then((user)=>{
if(user!=null){
var err=new Error('this user '+ req.body.username +' already exists');
err.status=403;
next(err);
}
else{
return user.create({
username:req.body.username,
password:req.body.password
});
}
})
.then(user=>{
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json({status:'Registration sussesful',user: user});
}), (err)=>next(err)
.catch((err)=>next(err));
});
//---------------------------- Login Code-----------------------------------------------
router.post('/login',(req,res,next)=>{
if(!req.session.user){
var authHeader=req.headers.authorization;
if(!authHeader){
var err=new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate','Basic');
err.status=401;
return next(err);
}
var auth=new Buffer.from(authHeader.split(' ')[1],'base64').toString().split(':');
var username=auth[0];
var password=auth[1];
User.findOne({username:username})
.then((user)=>{
if(user===null){
var err=new Error('User '+username +' does not exist');
err.status=403;
return next(err);
}
else if(user.password!=password){
var err=new Error('Your password is incorrect');
err.status=403;
return next(err);
}
else if(user.username===username&&user.password===password){
req.session.user='authenticated';
res.statusCode=200;
res.setHeader('Content-Type', 'text/plain');
res.end('You are authenticated!')
}
}).catch((err)=>next(err));
}
else{
res.status=200;
res.setHeader('Content-Type','text/plain');
res.end('You are already authenticated');
}
});
//--------------------------------- Logout code-------------------------------------------
router.get('./logout',(req,res)=>{
if(req.session){
req.session.destroy();
res.clearCookies('session_id');
res.redirect('/');
}
else{
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
module.exports = router;```
I have created the schemas properly I think there is some error in app.js or users.js file.
1.GET /signup - - ms - -(both GET and POST not working, it was a while I don’t know whats wrong)
2. please check below code
3.server.js. This this the app code that you have requested.Kindly go through it. Also the value for link is replaced by word link as it is private.
4. There are two files in this. Server.js and user.js kindly check it out.
var router = require("express").Router();
var User = require("../models/user.js");
router.get("/signup", function(req, res){
res.send("hello");
});
router.post('/signup', function(req, res, next){
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne( { email : req.body.email }, function(err, existingUser) {
if(existingUser){
console.log(req.body.email + "already exists");
return res.redirect("/signup");
}
else{
user.save(function(err, user){
if(err) return next(err);
res.send("New user has been added");
});
}
});
});
module.exports = router;
//server.js code
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var User = require("./models/user.js");
var ejs = require("ejs");
var engine = require("ejs-mate");
var app = express();
mongoose.connect('link', function(err){
if(err){
console.log(err);
}
else{
console.log("connected to database");
}
});
//middle ware
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.engine("ejs", engine);
app.set("view engine", "ejs");
var mainRoutes = require("./routes/main.js");
var userRoutes = require("./routes/user.js");
app.use(mainRoutes,function(err){
if(err){
console.log("error is here")
}
});
app.use(userRoutes, function(err){
if(err){
console.log("error is here in 2" );
}
});
//listen to port 3000
app.listen(3000, function(err){
if(err) throw err;
console.log("Server has started");
});
removed the call back function from app.use() and it worked.
-> this is my server.js. while i am trying to open it by using node server, it is showing cannot get/.
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/
var express = require('express');
var bodyParser = require('body-parser');
var User = require('./app/models/user');
var app = express();
var jwt = require('jwt-simple') var _ = require('lodash') var bcrypt = require('bcrypt')
app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
var secretkey = "supersecretkey"
app.post('/session', function(req, res, next) {
console.log(req.body.username);
User.findOne({
username: req.body.username
}).select('password').exec(function(err, user) {
if (err) {
return next(err)
}
if (!user) {
return res.send(401)
}
bcrypt.compare(req.body.password, user.password, function(err, valid) {
if (err) {
return next(err)
}
if (!valid) {
return res.send(401)
} //var test = {username:user.username}; //console.log(user.username); var token = jwt.encode({ username: req.body.username}, secretkey) res.json(token)
})
})
})
app.get('/user', function(req, res, next) {
var token = req.headers['x-auth'] console.log(token)
var auth = jwt.decode(token, secretkey)
//console.log(auth)
User.findOne({ username: auth.username
}, function(err, user)
{ res.json(user) }) })
app.post('/user', function(req, res) {
var user = new User({
username: req.body.username
}) bcrypt.hash(req.body.password, 10, function(err, hash) {
user.password = hash user.save(function(err, user) {
if (err) {
throw next(err)
} // res.send(201) res.json(user); }) })
})
app.listen(3000)
->This is my app.js.
"use-strict"
var express = require('express');
var router = express.Router(); // get an instance of the express Router
var morgan = require('morgan');
var bodyParser = require('body-parser');
var app = express();
/*app.use(morgan('dev'));*/
app.use('/public/app/controllers/routes', router);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
extended: true
})); // support encoded bodies
app.use(require('./config/auth'))
app.use('/api/users', require('./app/controllers/api/users'))
app.use('/api/sessions', require('./app/controllers/api/sessions'))
app.use('/api/products', require('./app/controllers/api/products'))
app.use('/api/companies', require('./app/controllers/api/companies'))
app.use('/api/stockists', require('./app/controllers/api/stockists'))
app.use('/api/employees', require('./app/controllers/api/employees'))
app.use('/api/sales', require('./app/controllers/api/sales'))
app.use('/', require('./app/controllers/static'))
var port = process.env.PORT || 3000
var server = app.listen(port, function() {
console.log('App listening at the ', port);
});
require('./websockets').connect(server)
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/
I have tried to post in MongoDB by using postman while posting a text i got a error of (Couldnt get any Response) It is not showing any error to Command nodemon Please help me where i did mistake ..! what i need to do ?
My index.js file is:-
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./configdb/database');
// Connection to database
mongoose.connect(config.database);
// Connection Success to DB
mongoose.connection.on('connected',() => {
console.log('Connected to the Database ' +config.database);
});
//on Error while Connecting
mongoose.connection.on('error',(err) => {
console.log('connection ERROR Try Again Database Failed to Connect ' +err);
});
const app = express();
const articles = require('./routers/articles');
// Port to start
const port = 2200;
// cors middleware
app.use(cors());
// Set Static Public folder
app.use(express.static(path.join(__dirname, 'public')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/articles',articles);
// Index Route
app.get('/', (req, res) => {
res.send('this is initial page for starting all session')
});
app.listen(port, () => {
console.log('server started in' + port)
})
my articles.js file is
const express = require('express');
const router = express.Router();
const config = require('../configdb/database');
const Article = require('../models/article');
// Register of article
router.post('/new-article', (req,res,next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
return;
article.save(function(err){
if(err){
res.json({success: false, msg: 'Failed to Register the Article' });
} else {
res.json({success: true, msg: 'New Article is Registered'});
}
});
});
module.exports = router;
my article.js file is
const mongoose = require('mongoose');
const config = require('../configdb/database');
const ArticleSchema = mongoose.Schema({
title:{
type: String,
}
});
const Article = module.exports = mongoose.model('Article', ArticleSchema)
But I have got the message from
article.title = req.body.title; and my error as follows:-
In articles.js you have return the function after displaying title cause the problem!
// Register of article
router.post('/new-article', (req, res, next) => {
let article = new Article();
article.title = req.body.title;
console.log(req.body.title);
// return;
article.save(function (err) {
if (err) {
res.json({
success: false,
msg: 'Failed to Register the Article'
});
} else {
res.json({
success: true,
msg: 'New Article is Registered'
});
}
});
});
I'm having trouble with my server routes, I had the server on heroku but now have it local to debug,
On browser inspection i get
404 (Not Found)
in browser window
Cannot GET /api/auth/register
My server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var logger = require('morgan');
var bodyParser = require('body-parser');
var databaseConfig = require('./config/database');
var router = require('./app/routes');
//CORS middleware
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
mongoose.connect(databaseConfig.url);
app.listen(process.env.PORT || 8080);
console.log("App listening on port 8080");
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
router(app);
My routes.js
var AuthenticationController = require('./controllers/authentication'),
ExerciseController = require('./controllers/exercises'),
express = require('express'),
passportService = require('../config/passport'),
passport = require('passport');
var requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
exerciseRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
//authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/register', function(req, res){
AuthenticationController.registerUser
});
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.get('/protected', requireAuth, function(req, res){
res.sendStatus({ content: 'Success'});
});
// Exercise Routes
apiRoutes.use('/exercises', exerciseRoutes);
exerciseRoutes.get('/', requireAuth, AuthenticationController.roleAuthorization(['client','trainer','admin']), ExerciseController.getExercises);
exerciseRoutes.post('/', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.createExercise);
exerciseRoutes.delete('/:exercise_id', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.deleteExercise);
// Set up routes
app.use('/api', apiRoutes);
}
And my Controller Authentication.js :
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var authConfig = require('../../config/auth');
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role,
trainer: request.trainer,
programs: request.programs
};
}
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
console.log(userInfo)
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
exports.registerUser = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
var trainer = req.body.trainer;
var programs= req.body.programs;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role,
trainer: trainer,
programs: programs
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
I dont have much experience with express/node so im not sure where im going wrong, could be something simple im just not able to see, anyways any help is greatly appreciated , not sure if you need more info, this is going to be the back end for an ionic 2 app