node - express入门

搭建express服务

npm安装express框架

npm install express --save

新建app.js文件

const express = require("express")
const http = require("http")
const app = express()

const server = http.createServer(app)
server.listen('8888')

app.use('/', (req, res) => {
  res.end('hello express')
})

中间件

上面代码中,app.use()为一个中间件,第一个参数(非必选)匹配url文件路径,如localhost:8808/shop中将会匹配'/shop',匹配成功执行回调函数,匹配失败则跳过此中间件。app.use('/')匹配任意文件路径,中间件将按代码顺序依次执行

app.use('/shop', (req, res, next) => {  // 匹配请求中文件路径以'/shop'开头的url
  console.log('shop')
  next()  // 需要执行next()进行下一步
})

app.get('/shop', (req, res, next) => {  // 只匹配get请求中文件路径以'/shop'开头的url
  console.log('shop1')
  console.log(req.query)  // 获取get请求中请求参数,json对象形式
  next()
})

app.post('/shop', (req, res, next) => {  // 只匹配post请求中文件路径以'/shop'开头的url
  console.log('shop2')
  next()
})

获取post请求参数

安装body-parser模块,用于处理以x-www-form-urlencoded、json传输的数据

npm install body-parser --save
const express = require("express")
const http = require("http")
const bodyParser = require('body-parser')

const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

const server = http.createServer(app)
server.listen('8888')

app.post('/shop', (req, res, next) => {
  console.log(req.body)  // post请求中的数据,json形式
  next()
})

app.use((req, res) => {
  res.end('hello express')
})

使用中间件的其他形式(不匹配文件路径),中间件中的req,res都是公用的,可进行数据的传递

function middleware1 ()  {
  return function (req, res, next) {
    req.array = []  // 为req对象添加array属性(数组类型)
    console.log('middleware1')
    next()
  }
}

function middleware2 (req, res, next)  { 
  req.array.push(1)
  console.log('middleware2')
  next()
}

function middleware3 (req, res, next)  { 
  req.array.push(2)
  console.log('middleware3')
  next()
}

app.use(middleware1(), [middleware2, middleware3])
app.use([middleware1(), middleware2, middleware3])

app.use((req, res) => {
  console.log(req.array)  // 输出 [1, 2]
})

中间件错误处理

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值