express基本用法

express

const express = require('express')
const app = express()
app.listen(8080, () => {
  console.log('port created successfully')
})

 

express会把所有的请求方式都作为方法挂载到app对象中,客户端发送请求并且会执行对应的回调函数

const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
    res.send("ok")
})
app.listen(8080, () => {
  console.log('port created successfully')
})

接收GET数据

const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
    let GET = req.query
    console.log(GET)
    res.send("ok")
})
app.listen(8080, () => {
  console.log('port created successfully')
})

接收POST数据

const bodyParser = require(body-parser)
const express = require('express')
const app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', (req, res, next) => {
    let POST = req.body
    console.log(POST)
    res.send("ok")
})
app.listen(8080, () => {
  console.log('port created successfully')
})

处理session

const cookieSession = require('cookie-session')
const express = require('express')
const app = express()
app.use(cookieSession({
  name: 'session',
  keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  req.session.views = 1
  res.send("ok")
})

app.listen(3000)

 

路由处理

//https://xxx.com/user/1.html
//https://xxx.com/user/2.html

const routerUser = express.Router()
app.use("/user", routerUser)
routerUser.get("/1.html", function (req, res) {
  res.send("1")
})
routerUser.get("/2.html", function (req, res) {
  res.send("2")
})

模板适配

const consolidate = require('consolidate')
app.set("view engine", "html");
app.set("view", "./template");
app.engine("html", consolidate.ejs)

app.get('/', function () {
  res.render("index.ejs", {})
})

处理文件

app.use(express.static('./dist'))

 

处理404

app.use((req, res, next) => {
  res.sendFile(path.resolve(__dirname, './404.html'))
})

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值