Node.js服务器在端口3000上运行和侦听但Localhost:3000没有发送任何数据

时间:2018-04-17 05:12:54

标签: javascript node.js express

因此服务器正在运行并正在侦听未被阻止的端口3000 据我所知,但是当我尝试加载页面时,它会挂起一段时间,然后才会提供以下消息:

"此页面无效 localhost没有发送任何数据。 ERR_EMPTY_RESPONSE

我不确定为什么即使我调整get(' /")主页以简化某些内容,我也无法获得任何结果。通过终端也没有任何错误,因此我不确定如何诊断问题。

我的app.js代码:

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');


mongoose.connect('mongodb://localhost/nodekb');
let db = mongoose.connection;

// Check connection
db.once('open', function(){
  console.log('Connected to MongoDB');
});

// Check for DB errors
db.on('error', function(err){
  console.log(err);
});

// Init App
const app = express();

// Bring in Models
let Article = require('./models/article');

// Load View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

// Set Public Folder
app.use(express.static(path.join(__dirname, 'public')));

// Express Session Middleware
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
}));

// Express Messages Middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Express Validator Middleware
app.use(expressValidator);

// Home Route
app.get('/', function(req, res){
  Article.find({}, function(err, articles){
    if(err){
      console.log(err);
    } else {
      res.render('index', {
        title:'Articles',
        articles: articles
      });
    }
  });
}); 

// Route Files
let articles = require('./routes/articles');
let users = require('./routes/users');
app.use('/articles', articles);
app.use('/users', users);

app.listen(3000, function(){
  console.log("We are running on port 3000");
});

1 个答案:

答案 0 :(得分:0)

我认为问题是你的查询是空数组。 我在查询回调中添加了条件,以检查文章数组长度

app.get('/', function(req, res){
    Article.find({}, function(err, articles){
          if(err){
              console.log(err);
              res.json(err);
          }else if(articles.length == 0){
              console.log("Articles not found");
              res.json({error : "Articles not found"});
          } else {
              console.log("Articles found");
              res.render('index', {
                  title:'Articles',
                  articles: articles
              });
          }
      });
}); 

我希望它会对你有所帮助。