1. 程式人生 > >express基本用法

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'))
})