我正在制作一个简单的待办事项列表应用,但我收到错误无法获取/
我认为它与不创建归属路由有关,而且index.ejs中可能存在错误,但不确定它究竟是什么。任何帮助是极大的赞赏 !谢谢 !!
app.js
// Dependencies
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
passport = require('passport'),
passportLocal = require('passport-local');
// MongoDB
mongoose.connect('mongodb://localhost/todos');
// Express
var app = express();
// Configuration
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// app.use(cookieParser);
app.use(expressSession({
secret: 'secret-key',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'bower_components')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Route
app.use('/todo', require('./routes/todo'));
app.use('/', require('./routes/user'));
// Start Server
app.listen(3000);
console.log('TODO app is running...');
routes / user.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router(),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
passport = require('passport'),
passportLocal = require('passport-local');
require('../models/user');
var User = mongoose.model('user');
passport.use( new passportLocal.Strategy(function(username, password, done){
User.findOne({ username: username }, function (err, user) {
console.log(user);
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (user.password != password) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
router.get('/login', function(req, res){
if(req.isAuthenticated()){
res.redirect('/todo');
}
res.render('login', { message: req.session.messages });
});
router.post('/login', loginPost);//passport.authenticate('local'), function(req, res){
// res.redirect('/todo');
// });
function loginPost(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
req.session.messages = info.message;
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) {
req.session.messages = "Error";
return next(err);
}
// set the message
return res.redirect('/todo');
});
})(req, res, next);
}
router.get('/logout', function(req, res){
req.logout();
req.session.messages = "";
res.redirect('/login');
});
router.get('/signup', function(req, res){
if(req.isAuthenticated()){
res.redirect('/todo');
}
res.render('signup');
});
router.post('/signup', function(req, res){
new User({username: req.body.username, password: req.body.password}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/login');
});
});
module.exports = router;
routes / todo.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
require('../models/todo');
require('../models/user');
var todo = mongoose.model('todo');
function isAuthenticated(req, res, next) {
// CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
// you can do this however you want with whatever variables you set up
if (req.isAuthenticated())
return next();
// IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
res.redirect('/login');
}
router.get('/', isAuthenticated, function(req, res){
console.log(req.session.passport.user);
var User = mongoose.model('user'), userData;
User.find({ _id: req.session.passport.user}, function(err, user){
console.log(user);
userData = user; return true;
}).limit(1);
console.log(userData);
todo.find({user: req.session.passport.user}, function(err, todos){
res.render('index', {items:todos, userData:userData});
});
});
router.post('/add', function(req, res){
new todo({task: req.body.task, user: req.session.passport.user}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/todo');
});
});
router.get('/delete/:id', function(req, res){
todo.remove({_id: req.params.id}, function(err){
res.redirect('/todo');
});
});
router.post('/update', function(req, res){
todo.where({_id: req.body.id}).update({status: req.body.status}, function(err, doc){
if(err) res.json(err);
else res.send(200);
});
});
module.exports = router;
views / index.ejs
<!DOCTYPE html>
<html>
<head>
<title>EHad Todo App</title>
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="todo.css">
</head>
<body>
<div class="container">
<div class="row">
<div class=".col-md-6 .col-md-offset-3">
<section class="panel tasks-widget">
<header class="panel-heading">
<p class="bg-primary"><%= userData[0].username %> Todo list</p>
</header>
<div class="panel-body">
<div class="task-content">
<ul class="task-list">
<% for (var i = 0; i < items.length; i++) { %>
<li class="task-<%= items[i].status %>">
<div class="task-checkbox">
<input type="checkbox" class="task-list-check" value="<%= items[i]._id %>" <% if(items[i].status == 'done'){ %> checked <% }%> >
</div>
<div class="task-title">
<span class="task-title-sp"><%= items[i].task %></span><sub class="date"><%= items[i].date.toDateString() %></sub>
<div class="pull-right hidden-phone">
<a href="todo/delete/<%= items[i]._id %>"><button class="btn btn-danger btn-xs">x</i></button></a>
</div>
</div>
</li>
<% } %>
</ul>
</div>
<div class=" add-task-row">
<form action="todo/add" method="post">
<div class="form-group">
<input type="text" class="form-control" name="task" placeholder="ADD Task">
</div>
<button type="submit" class="btn btn-success btn-sm pull-right">Add New Tasks</button>
</form>
</div>
<span style="font-size:12px"><a href="logout">Logout</a></span>
<div><p class="bg-info">copyright By @emranulhadi 2015</p></div>
</div>
</section>
</div>
</div>
</div>
<script type="text/javascript" src="jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".btn-danger").on("click", function(e){
var r = confirm("Are You Sure? You want to DELETE!!!");
if (r == true) {
return true;
} else {
e.preventDefault();
return false;
}
});
$('.task-list-check').click(function() {
var taskStatus = "done";
if($(this).is(":checked")){
$(this).parent().parent().addClass('task-done');
} else {
$(this).parent().parent().removeClass('task-done');
taskStatus = "new";
}
$.post( "todo/update", {id: $(this).val(), status: taskStatus}, function( data ) {
console.log(data);
return true;
});
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
在routes/user.js
文件中,为/
定义另一个路由定义,并为索引路由呈现您想要的任何视图。
router.get('/', (req, res){
res.render("/path/to/view/file");
});