快递路由器无法获取/

时间:2018-02-15 22:09:55

标签: javascript express router

我有一个应用程序,我试图将路由移动到单独的文件。在尝试使用快速路由器时,我一直得到一个CAN NOT GET /。我的设置与我在其他应用程序中设置的方式相同,但无法使其正常工作。

这是在我的路线文件夹中:index.js

var express    = require('express');
var router     = new express.Router();
var Blog       = require('../models/blogpost'); 
var User       = require('../models/user');
var passport   = require('passport');

router.get("/", function(req, res){
 Blog.find({}, function(err, blogs){
  if(err){
      console.log(err);
  } else {
      res.render("index", {blogs: blogs});
  }
});
});

module.exports = router;

这是我的app.js文件:

var methodOverride   = require('method-override'),
LocalStrategy    = require('passport-local'),
bodyParser       = require('body-parser'),
nodeMailer       = require('nodemailer'),
passport         = require('passport'),
mongoose         = require('mongoose'),
express          = require('express'),
request          = require("express"),
router           = express.Router(),
User             = require('./models/user'),
Blog             = require('./models/blogpost'),  
Comment          = require('./models/comment'),  
middleware       = require('./middleware'),
app              = express(),
request          = require('request'),
indexRoutes      = require('./routes/index');

//==================================
//APP CONFIG
//==================================

// mongoose.connect("mongodb://localhost/amy_blog");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});

app.use(express.static(__dirname + "/public"));

app.use('/', indexRoutes);

=====================

app.listen(process.env.PORT, process.env.IP, function(){
console.log("================================");
console.log("The Blog server has started!");
console.log("================================");
});

非常感谢任何帮助。我一直想着这个问题。

2 个答案:

答案 0 :(得分:0)

您不想创建DateSeparator的新实例。

在路线文件中,从您分配express.Route()变量的位置删除new关键字。可能只是一个错字。

根据文档https://expressjs.com/en/guide/routing.html

答案 1 :(得分:0)

express.Router()实例是Express.js的中间件和路由系统。在您的代码中,您犯了两个错误:

  1. 使用新关键字致电express.Router()
  2. 未在应用中加载路由器模块

下面是一种可以使应用程序正常工作的简单方法:

const express = require('express');
const app = express();
const router = express.Router();

// This route handler is for demo purposes,
// you can replace it with your own route and add other routes as desired
router.get("/", (request, response) => {
  response.json({"message": "app works!"});
});

app.use("/", router); // Load the router module

app.listen(8080, () => 'Server started and is listening on port: 8080');