Nodejs服务器正在运行,并且本地主机未在快速项目上发送任何数据

时间:2019-03-03 13:08:32

标签: node.js express passport-local

我正在使用{。{3}}使用Node.js Express和mongodb来构建购物车,到目前为止没有问题,但是现在当我运行服务器时,它显示为'

  

服务器在端口3000上运行

'但是问题是当我连接到localhost:3000时,它显示,

  

此页面无法正常运行localhost没有发送任何数据。   ERR_EMPTY_RESPONSE

我检查了一些错误日志,但是没有用。数据库连接也正常工作,并且数据库正在获取数据

终端没有显示错误,如何解决

我的bin / www代码

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('shopping-cart:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

我的app.js代码

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');

var app = express();

mongoose.connect('mongodb://localhost:27017/shopping',{ useNewUrlParser: true });
require('./config/passport');

// view engine setup
app.engine('.hbs',expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecert', resave: false, saveUninitialized: false}));
app.use(flash);
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

我的index.js代码

var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var passport = require('passport');

var Products = require('../models/product');

var csurfProtection = csrf();
router.use(csurfProtection);

/* GET home page. */
router.get('/', function(req, res, next) {

  Products.find(function (err, docs) {
    var productChunks = [];
    var chunkSize = 4;
    for (var i = 0; i < docs.length; i += chunkSize) {
      productChunks.push(docs.slice(i, i + chunkSize))
    }
    res.render('shop/index', { title: 'Shopping Cart', products: productChunks });

  });
});

router.get('/user/signup', function (req, res, next) {
  res.render('user/signup',{csrfToken: req.csrfToken()})
});

router.post('/user/signup',passport.authenticate('local.signup', {
  successRedirect: 'user/profile',
  failureRedirect: 'user/signup',
  failureFlash: true

}));

router.get('user/profile', function (req, res, next) {
  res.render('user/profile')
});

module.exports = router;

和我的password.js代码

var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;

passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id,function (error, user) {
        done(err, user)
    })
});

passport.use('local.signup', new LocalStrategy({
    userNameFeild: 'email',
    passwordFeild: 'password',
    passReqToCallback: true
}, function (req, email, password, done) {
    User.findOne({'email': email}, function (err, user) {
        if (err) {
            return done(err);
        }
        if (user) {
            return done(null, false, {message: 'Email Already in use'})
        }
        var newUser = User;
        newUser.email = email;
        newUser.password = newUser.encryptPassword(password);
        newUser.save(function (err, result) {
            if (err) {
                return done(err);
            }
            return done(null, newUser);
        })
    })
}));

和我的product.js代码

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = new Schema({
    imagePath: {type: String, required: true},
    title: {type: String, required: true},
    description: {type: String, required: true},
    price: {type: Number, required: true}
});

module.exports = mongoose.model('product', schema);

请帮帮我

1 个答案:

答案 0 :(得分:0)

如果您对index.js中的Products.find的调用未返回任何内容,则该代码无法完成http事务。

建议您测试该情况并使用res.end()完成交易