首先新建一个目录mkdir myblog,在该目录下运行npm init 生成package.json
然后安装express,加--save写入package.json
npm i [email protected] --save
新建index.js并写入:
var express = require(‘express‘); var app = express(); app.get(‘/‘, function(req, res) { res.send(‘hello, express‘); }); app.listen(3000);
文件结构如下:
然后全局安装supervisor并启动:
npm install -g supervisor
supervisor --harmony index
supervisor 会监听当前目录下 node 和 js 后缀的文件,当这些文件发生改动时,supervisor 会自动重启程序
安装一个模版引擎ejs:npm i ejs --save
此时各文件代码如下:index.js:
var path = require(‘path‘); var express = require(‘express‘); var app = express(); var indexRouter = require(‘./routes/index‘); var userRouter = require(‘./routes/users‘); app.set(‘views‘, path.join(__dirname, ‘views‘));// 设置存放模板文件的目录 app.set(‘view engine‘, ‘ejs‘);// 设置模板引擎为 ejs app.use(‘/‘, indexRouter); app.use(‘/users‘, userRouter); app.listen(3000);
routes/index.js:
var express = require(‘express‘); var router = express.Router(); router.get(‘/‘, function(req, res) { res.send(‘hello, express‘); }); module.exports = router;
routes/users.js:
var express = require(‘express‘); var router = express.Router(); router.get(‘/:name‘, function(req, res) { res.render(‘users‘, { name: req.params.name }); }); module.exports = router;
views/header.ejs
<!DOCTYPE html> <html> <head> <style type="text/css"> body {padding: 50px;font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;} </style> </head> <body>
views/footer.ejs
</body> </html>
views/users.ejs:
<%- include(‘header‘) %> <h1><%= name.toUpperCase() %></h1> <p>hello, <%= name %></p> <%- include(‘footer‘) %>
运行:
访问localhost:3000/users/richard:
https://maninboat.gitbooks.io/n-blog/content/book/3.3%20%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E.html
时间: 2024-09-29 23:35:41