所以我一直试图解决这个问题已经有一段时间了,我在这里错过了一些东西。我试图确定在Express中设置路线的最佳做法。我想按文件分隔我设置的不同路线。我试图使用Express Router模块,但我无法使用它。这是我的主要服务器文件:
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错误。
答案 0 :(得分:2)
在你的第二个文件中只听/ route:
/* GET users listing. */
userRouter.get( '/', 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 );
});
由于您正在收听第一个文件app.use(&#34; / users&#34; ..)