nodejs:使用res.redirect工作的路由显示404未找到

时间:2016-10-30 22:22:28

标签: javascript node.js mongodb redirect express

我正在使用nodejs,express和mongodb构建一个Web应用程序,我是一个初学者。 这是我的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 expressValidator=require('express-validator');
var expressSession=require('express-session');
var login = require('./routes/login');
var homepage = require('./routes/homepage');
var searchStudents=require('./routes/searchStudents');
var addStudents=require('./routes/addStudents');
var editStudents=require('./routes/editStudents');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//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(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 app.use(expressSession({secret:'max',saveUninitialised:false,resave:false}));
app.use('/', login);
app.use('/homepage', homepage);
app.use('/homepage/SearchStudents',searchStudents);
app.use('/homepage/addStudents',addStudents);
app.use('/homepage/editStudents',editStudents);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
  message: err.message,
  error: err
  });
 });
 }
 app.use(function(err, req, res, next) {
 res.status(err.status || 500);
 res.render('error', {
 message: err.message,
 error: {}
 });
 });
 module.exports = app;`

我的观点与我的路线名称相似。 我可以使用post方法从登录重定向到主页 但我不能从主页重定向到searchStudents.It显示404错误 请帮我解决这个路由问题。 这是我的login.js:

var express = require('express');
var router = express.Router();
var item;
var output=null;
var mongo =require('mongodb').MongoClient;
var assert=require('assert');
var url='mongodb://localhost:27016/test';
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('login');

});
router.post('/hompage', function(req, res, next) {
    item={
        user:req.body.username,
        password:req.body.password
    };
    console.log("this is the username/// "+item.user);
    mongo.connect(url,function(err,db){
        assert.equal(null,err);
        result=db.collection('users').findOne({username:item.user},{id:0,password:0},function(err,data){
        if(err)
        {

            db.close();
            res.redirect('/');
        }
        else if(data==null)
        {
            db.close();
            res.redirect('/');
        }
        else
        {
            //console.log(data);
            db.close();
            res.redirect('/homepage');

        }

});
        });

});

这是我的login.ejs

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>

<h1 align="center">Login Page</h1>
<form action="/hompage" method="post">
<table align="center">
<tr>
<td><i>Enter Username</i>
</td>
<td>        
<input type="text" name="username" placeholder="enter username">
</td>   
</tr>
<tr>
<td><i>Enter Password</i></td>
<td>    
<input type="password" name="password" placeholder="enter password">
</td>   
</tr>
<tr>
<td>
<input type="submit" value="submit">
</td>   
</tr>       
</table>
</form>

</body>
</html>

这是我的主页.js:

var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('homepage');
});
router.post('/homepage/searchStudents', function(req, res, next) {
res.redirect('/homepage/searchStudents');
});
module.exports = router;

这是我的主页.js

<html>
<head>
</head>
 <body>
 <h1>homepage</h1>
 <form action="/homepage/searchStudents" method="post">
 <input type="submit" value="Search Studetns">
 </form>
 <form action="/homepage/addStudents" method="post">
 <input type="submit" value="Add Studetns">
 </form>

 </body>
 </html>

1 个答案:

答案 0 :(得分:0)

哇..你的代码有点乱,所以想象它我在你的404处理程序上犯了一个错误,你用next()函数传递throw,所以也许当它得到404时你不是重定向可以拦截它并呈现您的自定义404页面。

如何拦截这些状态页面(404和500)的示例如下:

// Handle 404
app.use(function(req, res) {
  res.status(400);
  res.render('errors/404', { title: '404' });
});

// Handle 500
app.use(function(error, req, res, next) {
  console.log(error);
  res.status(500);
  res.render('errors/500', { title: '500' });
});