1
所以我一直在努力工作一段時間現在,我在這裏失去了一些東西。我正在嘗試確定在Express中設置路線的最佳做法。我想分開我通過文件設置的不同路線。我正在嘗試使用Express Router模塊,但我無法使其工作。這是我的主服務器上的文件:不能GET/POST與高速路由器()
var express = require('express');
var handlebars = require('express-handlebars');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Models
var db = require('./models/db.js');
var user = require('./models/user.js');
// Routes/Controllers
var routes = require('./routes/index.js');
var userRouter = require('./routes/users.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
// uncomment after placing your favicon in /public
//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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Routing Table
app.use('/', routes);
// User
app.use('/users', require('./routes/users'));
這裏是用戶的路線:
var express = require('express');
var userRouter = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
userRouter.use(bodyParser.urlencoded({ extended: true }));
userRouter.use(methodOverride(function(req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}}));
/* GET users listing. */
userRouter.get('/users', function(req, res, next) {
console.log('users GET');
mongoose.model('User').find({}, function(err, users) {
if(err) {
console.error(err);
} else {
console.log(users);
res.render('users/index', { users: users });
}
});
})
.post(function(req, res, next) {
console.log(req);
});
module.exports = userRouter;
,這裏是我試圖與發帖的形式:
<form name='create-users' action='/users' method='post' >
<h6>Create Account</h6>
<fieldset>
<label for='username'>User Name</label>
<input name='username' id='newname' type='text' placeholder='User Name'>
<label for='email'>Email</label>
<input name='email' id='email' type='text' placeholder='Email'>
<label for='newpassword'>Password</label>
<input name='password' id='newpassword' type='text' placeholder='Password'>
<button type='submit'>Create</button>
</fieldset>
</form>
我我知道我不需要這些文件,但這只是給我一個404錯誤。