likes
comments
collection
share

Node - Express

作者站长头像
站长
· 阅读数 20

Express是什么

  • Express 是一个保持最小规模的灵活的 Node.js Web 应用程序开发框架,为 Web 和移动应用程序提供一组强大的功能。
  • 使用您所选择的各种 HTTP 实用工具和中间件,快速方便地创建强大的 API。
  • Express 提供精简的基本 Web 应用程序功能,而不会隐藏您了解和青睐的 Node.js 功能。
  • 中文地址:https://www.expressjs.com.cn/

使用

下载

npm i express --save

构建指定文件

// index.js 举例,另外 `.js` 可以省略
node index.js

修改完代码自动构建

  • nodemon: 第三方插件,就是为了解决 node 每次修改完成以后都需要重新构建的问题
  • 下载:npm i nodemon -g,这种工具类的最好都是全局安装
  • 使用方式:nodemon index.js

API

hello world
var express = require('express')

// 创建服务器,相当于http.createServer
var app = express();

app.get('/', function(req,res) {
    res.send('hello')
})

app.listen(9527,function() {
    console.log('app is running at port 9527')
})
基本路由
// get
app.get('/', function(req,res) {
    res.send('get')
})
// post
app.post('/', function(req,res) {
    res.send('post')
})
静态服务
// 公开指定目录
// 只要这样做了,你就可以直接通过/public/xx的方式访问public下的所有资源了
app.use('/public',express.static('./public'))       // 通过localhost:9527/public/index.html
// 还可以省略第一个参数,但是省略第一个参数的时候,访问方式中也要省略掉对应的路径
app.use(express.static('./static'))                 // 访问方式变成了localhost:9527/index.html
// 还有一种是给公开目录取别名
app.use('/abc',express.static('./pages'))       // 通过localhost:9527/abc/index.html
Express中使用art-template

安装:

npm i --save art-template
npm i --save express-art-template

配置:

/*
    第一个参数表示当渲染以 .art 结尾的文件的时候,使用 art-template 引擎。当然你可以不使用 .art
    这里配置是啥,下面的render中就要使用啥
    我们在下载以来的时候,下载了 express-art-template 和 art-template,但是我们并没有引入使用,是因为前者使用了后者
*/
// app.engine('art', require('express-art-template'))
app.engine('html', require('express-art-template'))

使用:

/*
    express 为 response(res) 这个响应对象提供了一个方法:render
    不过 render 默认是不能使用的,但是如果配置了 art-template 模板引擎就可以使用了
    res.render('html模板名',{模板数据})
    第一个参数不能写路径,默认会去项目中的views目录中查找该模板文件,即所有视图文件都默认放在views目录中
    当然也是可以更改默认路径的,修改方式是app.set('views','pages')。把默认路径从views修改为pages
*/
app.get('/',function(req,res) {
    console.log(req.query)
    // res.render('index.art')
    res.render('index.html',{
         title: "你号啊"
    })
})
Express中使用post请求

Express 中没有内置解析Psot请求体的API,所需需要使用第三方的包 body-parser

安装:

npm i --save body-parser

配置:

const express = require('express')
// 引入中间件,用来解析Post请求
const bodyParser = require('body-parser')

const app = express()


/*
    配置 body-parser (中间件,专门用来解析 Post请求体)
    只要加入这个配置,则在 req 请求对象上就多了一个 body 属性
    也就是说,我们可以直接使用 req.body 来获取 Post 请求体重的数据了
*/
// parser application/x-www.form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// parser application/json
app.use(bodyParser.json())


app.post('/',function(req,res) {
    console.log(req.body)
})

app.listen('9530',function() {
    console.log('running at port localhost:9530')
})