1 Mencipta projek dengan express4, dan laluan "/" dan "/users" lalainya boleh diakses oleh itu, tambahkan laluan dan fail laluan berdasarkan fail entrinya, dan hasilkan templat ejs yang sepadan. halaman utama boleh diakses , dan boleh disambungkan ke fail gaya seperti biasa, manakala laluan lain memaparkan 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 %>
Sila berikan saya jawapan anda.
//Salah satu fail laluan (login.js)
router.get('/', function(req, res, next) {
res.render('login', { title: 'Login' });
} );
Tukar kepada ini sahaja
Oleh kerana laluan padanan
app.use('/login',router);
router.get('/login',()=>{})
ialah /login/login
Tukar laluan akses kepada localhost:3000/login/log masuk