无法使用nodejs,mongodb从数据库获取ID

时间:2016-01-15 16:54:29

标签: node.js mongodb

我正在尝试构建一个RESTful api,用于存储带有密码和电子邮件的用户以及带有评论和回复的产品。此时此刻我正在尝试从名为Products的数据库中获取一些数据,并且我想显示一个产品给出他的身份证明的信息,但我收到了:

无法获取/ api / productinfo /:56990ef287f61aa20fdf5288

这是server.js

    var express     = require('express');
var app         = express();
var bodyParser  = require('body-parser');
var morgan      = require('morgan');
var mongoose    = require('mongoose');
var passport    = require('passport');
var config      = require('./config/database'); // get db config file
var User        = require('./app/models/user'); // get the mongoose model
var Products      = require('./app/models/products'); //get the mongoose model
var Makeissue     = require('./app/models/makeissue'); //get the mongoose model
var port        = process.env.PORT || 8080;
var jwt         = require('jwt-simple');

// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// log to console
app.use(morgan('dev'));

// Use the passport package in our application
app.use(passport.initialize());

// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
  res.send('The API is at http://localhost:' + port + '/api');
});

// connect to database
mongoose.connect(config.database);

// pass passport for configuration
require('./config/passport')(passport);

// bundle our routes
var apiRoutes = express.Router();


// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
  if (!req.body.name || !req.body.password || !req.body.email) {
    res.json({success: false, msg: 'Please pass name and password and email.'});
  } else {
    var newUser = new User({
      name: req.body.name,
      password: req.body.password,
      email: req.body.email
    });
    // save the user
    newUser.save(function(err) {
      if (err) {
        return res.json({success: false, msg: 'Username already exists.'});
      }
      res.json({success: true, msg: 'Successful created new user.'});
    });
  }
});

// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
  User.findOne({
    name: req.body.name
  }, function(err, user) {
    if (err) throw err;

    if (!user) {
      res.send({success: false, msg: 'Authentication failed. User not found.'});
    } else {
      // check if password matches
      user.comparePassword(req.body.password, function (err, isMatch) {
        if (isMatch && !err) {
          // if user is found and password is right create a token
          var token = jwt.encode(user, config.secret);
          // return the information including token as JSON
          res.json({success: true, token: 'JWT ' + token});
        } else {
          res.send({success: false, msg: 'Authentication failed. Wrong password.'});
        }
      });
    }
  });
});


// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
  if (!req.body.name || !req.body.serialnumber) {
    res.json({success: false, msg: 'Please pass name and serial number.'});
    } else {
    var newProducts = new Products({
      name: req.body.name,
      serialnumber: req.body.serialnumber     
    });
    // save the Product
    newProducts.save(function(err) {
      if (err) {
        return res.json({success: false, msg: 'Product already exists.'});
      }
      res.json({success: true, msg: 'Successful created new Product.'});
    });
  }
});

apiRoutes.post('/resources/createpost', function(req, res) {
  if (!req.body.issue) {
    res.json({success: false, msg: 'Please pass a issue.'});
    } else {
    var newMakeissue = new Makeissue({
      issue: req.body.issue    
    });
    // save the Product
    newMakeissue.save(function(err) {
      if (err) {
        return res.json({success: false, msg: 'Post already exists.'});
      }
      res.json({success: true, msg: 'Successful created new post.'});
    });
  }
});





 apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
  if (!req.param('name')) res.status(400).send("Please send a proper name");
  else{
      access.findProductsByName(Products, req.param('name'), function(Products) {
        if (!text) res.status(500).send("server error");
      });
    }
  });



// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
  if (token) {
    var decoded = jwt.decode(token, config.secret);
    User.findOne({
      name: decoded.name
    }, function(err, user) {
        if (err) throw err;

        if (!user) {
          return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
        } else {
          res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
        }
    });
  } else {
    return res.status(403).send({success: false, msg: 'No token provided.'});
  }
});

getToken = function (headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
      return parted[1];
    } else {
      return null;
    }
  } else {
    return null;
  }
};


// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;


// Start the server
app.listen(port);
console.log('http://localhost:' + port);

和database.js

module.exports = {
  'secret': 'di.ionio.gr',
  'database': 'mongodb://localhost/firstapp'
};

和package.json

{
  "name": "firstapp",
  "main": "server.js",
  "dependencies": {
    "bcrypt": "^0.8.5",
    "body-parser": "~1.9.2",
    "express": "~4.9.8",
    "jwt-simple": "^0.3.1",
    "mongoose": "~4.2.4",
    "mongodb" : "~1.2.5",
    "morgan": "~1.5.0",
    "passport": "^0.3.0",
    "passport-jwt": "^1.2.1"
  }
}

2 个答案:

答案 0 :(得分:0)

只是一个疯狂的猜测,但不应该你的app.get请求使用_id,如果我没有误会,你试图根据它生成的ID获取mongo中的项目,而不是一个自定义的?

答案 1 :(得分:0)

错误表示没有定义此类路由'/api/productinfo/:name'

根据您的代码,您为路由apiRoutes定义'/api'中间件。这意味着您在apiRoutes上定义的所有路线都将以'/api'开头。例如,您可以制作' GET'请求'/api/memberinfo'

'/resources/productinfo/:name'中间件上定义apiRoutes路由,这意味着您的请求应转到'api/resources/productinfo/:name'。因此,您的请求应更改为:

/api/resources/productinfo/56990ef287f61aa20fdf5288