1.用express4创建了个项目,其默认的“/”和“/users”路径能够访问,因此在其入口文件的基础上添加路径和路径文件,并创建相应的ejs模板,结果首页能够访问,并可以正常连接到样式文件,其他的路径则显示404.
|
---public
|
---routes
|
---login.js(路由文件)
|
---view
|
---login.ejs(模板文件)
|
---app.js(入口)
//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 index = require('./routes/index');
var login = require('./routes/login');
var register = require('./routes/register');
var logout = require('./routes/logout');
var post = require('./routes/post');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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')));
app.use('/', index);
app.use('/login', login);
app.use('/register', register);
app.use('/logout', logout);
app.use('/post', post);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//路径文件之一(login.js)
var express = require('express');
var router = express.Router();
/* GET login listing and render page. */
router.get('/login', function(req, res, next) {
res.render('login', { title: '登录' });
});
module.exports = router;
//模板文件之一(这块应该没问题,被引入的我就不贴了)(index.ejs)
<%- include header %>
主页
<%- include footer %>
请诸位大大解答。
//路径文件之一(login.js)
router.get('/', function(req, res, next) {
res.render('login', { title: '登录' });
});
改成这样就可以了
因为
app.use('/login',router);
router.get('/login',()=>{})
的匹配路径是 /login/login
访问路径改为localhost:3000/login/login