Nodejs应用程序在访问表单页面时崩溃

Nodejs application crashes upon visiting form page

本文关键字:崩溃 表单 访问表 应用程序 访问 Nodejs      更新时间:2023-09-26

我遵循Udemy教程。到目前为止,一切都运行良好,直到我将应用程序连接到mongodb。应用程序运行良好,连接到数据库,但是当我访问应该显示数据库数据的表单页面时,应用程序崩溃并给出以下错误。

app.js文件

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var appRoutes = require('./routes/app');
var app = express();
mongoose.connect('localhost:27017/node-angular2');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
    next();
});
app.use('/', appRoutes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    return res.render('index');
});
module.exports = app;

路由器/app.js

var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.get('/', function (req, res, next) {
    User.findOne({}, function(err, doc) {
        if (err) {
            return res.send('Error!');
        }
        res.render('node', {email: doc.email});
    });
});
router.post('/', function(req, res, next) {
    var email = req.body.email;
    var user = new User({
        firstName: 'Max',
        lastName: 'Schwarz',
        password: 'super-secret',
        email: this.email
    });
    user.save();
    res.redirect('/');
});
module.exports = router;

错误日志

> node ./bin/www
events.js:160
      throw er; // Unhandled 'error' event
      ^
TypeError: Cannot read property 'email' of null
    at /Users/farooqkhan/Documents/Udemy/node-angular2/routes/app.js:11:39
    at Query.<anonymous> (/Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/mongoose/lib/model.js:3381:16)
    at /Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/kareem/index.js:259:21
    at /Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/kareem/index.js:127:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! udemy-nodejs-angular2@1.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the udemy-nodejs-angular2@1.0.0 start script 'node ./bin/www'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the udemy-nodejs-angular2 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node ./bin/www
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs udemy-nodejs-angular2
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls udemy-nodejs-angular2
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR!     /Users/farooqkhan/Documents/Udemy/node-angular2/npm-debug.log

2的例子。

然后我运行了一个mongodb IDE,我从github。它曾经工作得很好,但现在当我访问主页时,它也给出了以下错误:

> node app.js
(node:1054) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
adminMongo listening on host: http://0.0.0.0:1234
GET / 302 8.496 ms - 56
/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:237
          throw err
          ^
TypeError: Cannot read property 'indexOf' of undefined
    at module.exports (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/parse-mongo-url/index.js:10:10)
    at new Database (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongojs/lib/database.js:43:20)
    at module.exports (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongojs/index.js:5:12)
    at /Users/farooqkhan/Documents/mongoIDE/adminMongo/routes/index.js:58:22
    at connectCallback (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:315:5)
    at /Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:234:11
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! admin-mongo@0.0.3 start: `node app.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the admin-mongo@0.0.3 start script 'node app.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the admin-mongo package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs admin-mongo
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls admin-mongo
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR!     /Users/farooqkhan/Documents/mongoIDE/adminMongo/npm-debug.log

我不明白这是怎么回事。以前一切都很好,我不知道突然发生了什么事。我甚至尝试重新安装MongoDB,但没有任何帮助。

看起来集合没有数据,你能验证你的node-angular2模块有用户表,它有数据吗?

您可以通过第三方工具(如robomongo)或通过shell connect with mongo命令来完成此操作。

同时你可以修改你的代码来做一些错误处理

var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.get('/', function (req, res, next) {
    User.findOne({}, function(err, doc) {
        if (err) {
            return res.send('Error!');
        }
        if(doc){
           res.render('node', {email: doc.email});
        }else{
           res.render('node', {email: null});
        }
    });
});
router.post('/', function(req, res, next) {
    var email = req.body.email;
    var user = new User({
        firstName: 'Max',
        lastName: 'Schwarz',
        password: 'super-secret',
        email: email
    });
    user.save(function(err){
       if(err){
         console.log("couldn't save");
       }
       res.redirect('/');
    });
});
module.exports = router;

正如你所看到的,我已经修改了你的post call,并且在save函数的回调中调用了redirect,这意味着只有当用户被保存时才会重定向。

在未完成前一个操作的情况下调用res.json或res.redirect时,前一个操作将固有地取消。