gpt4 book ai didi

javascript - Nodejs路由器顺序

转载 作者:行者123 更新时间:2023-12-03 05:39:17 25 4
gpt4 key购买 nike

我正在使用:

express 4.14 node 7.0+ session 1.14+

<小时/>

我使用 webstorm 创建了 Nodejs 项目:

app.js

var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var user = require('./routes/user');

var app = express();

var check = function() {
!req.session.status ? res.redirect('/user/login') : next();
}

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

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(session({secret: "inline", resave: false, saveUninitialized: true, status: false}));

app.use('/', check, require('./routes/index'));
app.use('/user', require('./routes/user'));

module.exports = app;

index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

module.exports = router;

用户.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

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

module.exports = router;

当我请求localhost:3000时,页面提示我“重定向太多”,现在的url是localhost:3000/user/login

我的问题是什么?

最佳答案

修复:

var check = function(req, res, next) {
!req.session.status ? res.redirect('/user/login') : next();
}




但我会为你写出更漂亮的解决方案,希望你能想到:

app.js:

app.use(require('./routes'));

路线文件夹:

routes/
|- index.js
|- common/
|- auth.js
|- root/
|- index.js
|- posts.js
|- backend/
|- index.js
|- posts.js
...

1) routes/index.js :

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

// guarded routes
function guardFn(req, res, next) {
let authenticated = req.session && req.session.authenticated === true;
authenticated ? next() : res.redirect('/auth');
}
router.use('/backend', guardFn, require('./backend'));

// public routes
router.use('/auth', require('./common/auth'); // for auth purposes
router.use('/', require('./root')); // for routes that starts from /, try not to rewrite /backend, /auth

module.exports = router;

2) 路由/common/auth:

const
express = require('express'),
router = express.Router();
mongoose = require('mongoose'),
User = mongoose.model('user');

router.get('/', (req, res) => {
res.render('common/auth');
});

router.post('/', (req, res) => {
User
.findOne({
username: req.body.username,
password: req.body.password
})
.exec((err, user) => {
if(err) {
console.error(err);
return res.status(500).send('System error! Try again later');
}
if(!user) return res.redirect('back');
req.session.user = user._id;
req.session.authenticated = true;
res.redirect('/backend');
});
});

function logout(req, res, next) {
delete req.session.user;
req.session.authenticated = false;
next();
}
router.delete('/auth', logout, (req, res) => res.send({success: true}));
router.get('/auth/destroy', logout, res => res.redirect('/auth'));

module.exports = router;

3) routes/root/index.js :

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

router.get('/', (req, res) => {
res.render('site/welcome');
});

module.exports = router;

4) routes/root/posts.js :

const
express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
Post = mongoose.model('post');

router.get('/', (req, res) => {
Post
.find()
.skip((req.query.page-1)*10)
.limit(10)
.exec((err, posts) => {
res.render('site/posts/list', {posts});
});
});

router.get('/:id', (req, res) => {
Post
.findById(req.params.id)
.exec((err, post) => {
if(err) {
console.error(err);
return res.status(500).send('System error! Try again later');
}
res.render('site/posts/show', {post});
});
});

module.exports = router;

5) routes/backend/index.js :

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

router.get('/', (req, res) => {
res.render('backend/dashboard');
});

module.exports = router;

6) routes/backend/posts.js :

const
_ = require('lodash'),
express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
Post = mongoose.model('post');

router.get('/', (req, res) => {
Post
.find()
.skip((req.query.page-1)*50)
.limit(50)
.exec((err, posts) => {
res.render('backend/posts/list', {posts});
});
});

router.get('/:id', (req, res) => {
Post
.findById(req.params.id)
.exec((err, post) => {
if(err) {
console.error(err);
return res.status(500).send('System error! Try again later');
}
res.render('backend/posts/show', {post});
});
});

function updatePost(id, data, callback) {
Post
.findById(_id)
.exec((err, post) => {
if(err) return callback(err);
if(!post) return callback('not found');

post = _.extend(post, data);
post.save(() => callback(null, post));
});
}
router.put('/:id', (req, res) => {
updatePost(req.params.id, req.body, (err, post) => {
if(err) return res.status(500).send({success: false, err});
res.send({success: true, post});
});
});

router.post('/:id', (req, res) => {
updatePost(req.params.id, req.body, (err, post) => {
if(err) return res.status(500).send(err);
res.redirect('/backend/posts');
});
});

function createPost(data, callback) {
let post = new Post();
post = _.extend(post, req.body);
post.save((err) => callback(err, post));
}
router.post('/', (req, res) => {
createPost(req.body, (err, post) => {
if(req.xhr) {
if(err) return res.status(500).send({success: false, err});
return res.send({success: true, post});
}
if(err) return res.status(500).send(err);
res.redirect('/backend/posts');
});
});

module.exports = router;

关于javascript - Nodejs路由器顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40607738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com