admin管理员组

文章数量:1432230

I am trying to make one rest API in Nodejs. I have defined my model and taking reference of my model in my route and using that model. I have given all code details below. Please someone help me.

This is my router file:index.js

const routes = require('express').Router();
const User=require('./model');
const bcrypt=require('bcryptjs');
const config=require('../config');
routes.post('/register',function(req,res){
  var hashPassword=bcrypt.hashPassword(req.body.password,8);
  User.create({
    name:req.body.name,
    password:hashPassword,
    admin:req.body.admin
  },function(err,user){
    if(err){
      return res.status(500).send("There is the problem with registering");
    }
    var payload={
      "id":"user._id"
    }
    var token=jwt.sign(payload,config.secret,{
      expiresIn: 86400
    })
    res.status(200).send({
      auth:true,
      token:token
    })
  })
})

This is my Model: model.js

// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('User', new Schema({ 
    name: String, 
    password: String, 
    admin: Boolean 
}));

This is my server.js:

// Bring in our dependencies
const app = require('express')();
const routes = require('./routes');
const config=require('./config');
const mongoose=require('mongoose');
const bodyparser=require('body-parser');
const cluster=require('cluster');
const numCPUs = require('os').cpus().length;

//  Connect all our routes to our application

if(cluster.isMaster){
  console.log('Master process running');
  for(var i=0;i<=numCPUs;i++){
    cluster.fork(i);
}}else{
app.use('/api', routes);
app.set('port', 3000);
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.listen(app.get('port'));
console.log('Server listening on port ' + app.get('port'));
}

mongoose.connect(config.database);
mongoose.connection.on('connected',()=>{
  console.log("Database Connected");
})
mongoose.connection.on('error',(err)=>{
  if(err){
      console.log(err);
  }
})
cluster.on('exit',(worker,code,signal)=>{
  console.log('worker %d died (%s). Restarting...',worker.process.pid,code||signal);
  cluster.fork();
})

When I trying to post data from postman I am getting below error.

TypeError: Cannot read property 'password' of undefined
    at F:\project\node-project\jwt-auth\routes\index.js:14:49
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\project\node-project\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\project\node-project\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at F:\project\node-project\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\project\node-project\node_modules\express\lib\router\index.js:335:12)
    at next (F:\project\node-project\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\project\node-project\node_modules\express\lib\router\index.js:174:3)
    at router (F:\project\node-project\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (F:\project\node-project\node_modules\express\lib\router\index.js:317:13)
    at F:\project\node-project\node_modules\express\lib\router\index.js:284:7

I am unable to find where am I making mistake? someone please help me to identify the error.

I am trying to make one rest API in Nodejs. I have defined my model and taking reference of my model in my route and using that model. I have given all code details below. Please someone help me.

This is my router file:index.js

const routes = require('express').Router();
const User=require('./model');
const bcrypt=require('bcryptjs');
const config=require('../config');
routes.post('/register',function(req,res){
  var hashPassword=bcrypt.hashPassword(req.body.password,8);
  User.create({
    name:req.body.name,
    password:hashPassword,
    admin:req.body.admin
  },function(err,user){
    if(err){
      return res.status(500).send("There is the problem with registering");
    }
    var payload={
      "id":"user._id"
    }
    var token=jwt.sign(payload,config.secret,{
      expiresIn: 86400
    })
    res.status(200).send({
      auth:true,
      token:token
    })
  })
})

This is my Model: model.js

// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('User', new Schema({ 
    name: String, 
    password: String, 
    admin: Boolean 
}));

This is my server.js:

// Bring in our dependencies
const app = require('express')();
const routes = require('./routes');
const config=require('./config');
const mongoose=require('mongoose');
const bodyparser=require('body-parser');
const cluster=require('cluster');
const numCPUs = require('os').cpus().length;

//  Connect all our routes to our application

if(cluster.isMaster){
  console.log('Master process running');
  for(var i=0;i<=numCPUs;i++){
    cluster.fork(i);
}}else{
app.use('/api', routes);
app.set('port', 3000);
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.listen(app.get('port'));
console.log('Server listening on port ' + app.get('port'));
}

mongoose.connect(config.database);
mongoose.connection.on('connected',()=>{
  console.log("Database Connected");
})
mongoose.connection.on('error',(err)=>{
  if(err){
      console.log(err);
  }
})
cluster.on('exit',(worker,code,signal)=>{
  console.log('worker %d died (%s). Restarting...',worker.process.pid,code||signal);
  cluster.fork();
})

When I trying to post data from postman I am getting below error.

TypeError: Cannot read property 'password' of undefined
    at F:\project\node-project\jwt-auth\routes\index.js:14:49
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\project\node-project\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\project\node-project\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at F:\project\node-project\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\project\node-project\node_modules\express\lib\router\index.js:335:12)
    at next (F:\project\node-project\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\project\node-project\node_modules\express\lib\router\index.js:174:3)
    at router (F:\project\node-project\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (F:\project\node-project\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (F:\project\node-project\node_modules\express\lib\router\index.js:317:13)
    at F:\project\node-project\node_modules\express\lib\router\index.js:284:7

I am unable to find where am I making mistake? someone please help me to identify the error.

Share Improve this question asked Apr 7, 2018 at 9:40 SUBHASIS MONDALSUBHASIS MONDAL 7231 gold badge9 silver badges20 bronze badges 3
  • I think it's because you're registering body parser AFTER your routes. Check this out and see if it helps stackoverflow./a/48132442/8954866 – vapurrmaid Commented Apr 7, 2018 at 9:43
  • I am not getting that error now. Thank you for the help. I am getting a new error. Trying for that fix. TypeError: bcrypt.hashPassword is not a function – SUBHASIS MONDAL Commented Apr 7, 2018 at 9:59
  • I do not see hashPassword listed in the bcrypt api, maybe you mean hash ? npmjs./package/bcrypt#api – vapurrmaid Commented Apr 7, 2018 at 10:06
Add a ment  | 

1 Answer 1

Reset to default 4

I am unable to find where am I making mistake? someone please help me to identify the error

The error has to do with how the express stack works. The order in which you register middleware, routes etc matters in express.

From the Express JS Guide:

An Express application is essentially a series of middleware function calls.

It may help to visualize an express application as a stack of function calls in series.

This means that when you do the following:

const routes = require('./routes');
app.use('/api', routes);
.
.
.
app.use(bodyparser.json());

You're saying to use body-parser after the routes in your stack, hence why you get the error TypeError: Cannot read property 'password' of undefined, as in your routes definition, req.body hasn't yet been populated by body-parser.

There are generally two ways to fix this:

1) change the order:

app.use(bodyparser.json())
.
.
.
app.use('/api', routes);

2) Use body-parser as middleware in your routes file:

const routes = require('express').Router();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()

routes.post('/register', jsonParser, function(req,res){
  ...
})

本文标签: javascriptCannot read property 39password39 of undefined in Node ApiStack Overflow