Express
原生的http在某些方面表现不足以应对开发需求,需要使用框架加快开发效率,让我们的代码高度统一。
在node中很多Web开发框架,此处学习express为主
官网:http://expressjs.com/
起步
安装
npm install --save express
hello world
//生成默认的package.json
//npm init -y
var express = require('express')
var app = express()
app.get('/',function (req,res) {
res.send('hello world')
})
app.listen(3000,function () {
console.log('express app is running')
})
基本路由
什么是路由(router)?
作为分发的。路由其实就是一张表,表中存储着具体的映射关系。
当请求’/xxx’的时候,执行后面对应的function
路由器
- 请求方法
- 请求路径
- 请求处理函数
get:
//当你以GET方法请求/的时候,执行对应的处理函数
app.get('/',function (req,res) {
res.send('hello world')
})
app.get('/login',function (req,res) {
res.send('login page')
})
post:
//当你以POST方法请求/的时候,执行对应的处理函数
app.post('/',function (req,res) {
res.send('Got a Post request')
})
静态服务
//直接访问public中的资源
app.use(express.static('./public'))
//必须是/a/public目录中的资源具体路径,就是给public起了个别名叫a
//也就是use中第一个参数是在浏览器输入的url,第二个参数是实际的指定的目录名字
app.use('/a/',express.static('./public/'))
//大多数用的方式
//当以/public/开头的时候,去./public/目录中找对应的资源
app.use('/public/',express.static('./public'))
在Express中使用art-template模板引擎
安装
npm install --save art-template
npm install --save express-art-template
配置
//配置使用art-template模板引擎
//第一个参数表示当渲染以.art结尾的文件的时候,使用art-template模板引擎
//express-art-template是专门用来在Express中把art-template整合到Express中
//虽然我们在这没有需要用到art-template,但是express-art-template依赖了它,所以也要安装一下
// app.engine('art',require('express-art-template'))
app.engine('html',require('express-art-template'))
使用
//Express为Response响应对象提供了一个方法:render
//render方法需要配置模板引擎才能使用
//res.render(