我想问这段代码的准确路径是什么?
发布于 9天前 作者 dean5277 174 次浏览 来自 问答

QQ图片20150124171807.png 新手。。。 上面是目录结构,index.html 在views目录下 ** 访问localhost:3000 可以看到页面,但访问 localhost:3000/index.html 却显示Cannot GET /index.html. 我想问准确的全路径应该是那个?**

app.js

var express = require(‘express’); var routes = require(‘./routes’);

var path = require(‘path’);

var favicon = require(‘serve-favicon’); var logger = require(‘morgan’); var methodOverride = require(‘method-override’); var session = require(‘express-session’); var bodyParser = require(‘body-parser’); var multer = require(‘multer’); var errorHandler = require(‘errorhandler’); var ejs = require(‘ejs’); var http = require(‘http’); var app = express();

// all environments app.set('port’, process.env.PORT || 3000); app.set('views’, path.join(__dirname, ‘views’)); app.engine('.html’, ejs.__express); app.set('view engine’, ‘html’);// app.set('view engine’, ‘ejs’); app.use(favicon(__dirname + ‘/public/favicon.ico’)); app.use(logger(‘dev’)); app.use(methodOverride()); app.use(session({ resave: true, saveUninitialized: true, secret: ‘uwotm8’ })); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(multer()); app.use(express.static(path.join(__dirname, ‘public’)));

// development only if (‘development’ == app.get(‘env’)) { app.use(errorHandler()); } app.get('/’, routes); app.get('/home’, routes); app.listen(app.get(‘port’), function(){ console.log('Express server listening on port ' + app.get(‘port’)); });

routes目录下的 index.js

var express = require(‘express’); var router = express.Router();

/* GET home page. */ router.get('/’, function(req, res, next) {

res.render('index’, { title: ‘Express’ }); });

exports.index = function(req, res){ res.render('index’, { title: ‘Index’ }); }; exports.login = function(req, res){ res.render(‘login’, { title: ‘用户登陆’}); }; exports.doLogin = function(req, res){ var user={ username:’admin’, password:’admin’ } if(req.body.username===user.username && req.body.password===user.password){ res.redirect(‘/home’); } res.redirect(‘/login’); }; exports.logout = function(req, res){ res.redirect(‘/’); }; exports.home = function(req, res){ var user={ username:’admin’, password:’admin’ } res.render('home’, { title: 'Home’,user: user}); };

module.exports = router;

2 回复

看看路由那一块,localhost:3000 可以看到页面,是因为执行了 index.js里面 / 路由 ,但访问 localhost:3000/index.html 却显示Cannot GET /index.html 是因为 没有 index.html的路由。这是用express开发最基础的东东

@skipify 理解了,哈哈,谢谢

回到顶部