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