寫一個小介面,用postman測驗介面是否可行????
import express from 'express'
import config from './config'
import router from './router'
import queryString from 'querystring'
const app = express()
app.use('/node_modules', express.static(config.node_modules_path))
app.use('/public', express.static(config.public_path))
// 決議處理表單 POST 請求體中間件
app.use((req, res, next) => {
// 由于表單 POST 請求可能會攜帶大量的資料,所以在進行請求提價的時候會分為多次提交
// 具體分為多少次進行提交不一定,取決于資料量的大小
// 在 Node 中,對于處理這種不確定的資料,使用事件的形式處理
// 這里可以通過監聽 req 物件的 data 事件,然后通過對應的回呼處理函式中的引數 chunk 拿到每一次接收到的資料
// data 事件觸發多少次,不一定
// 當資料接收完畢之后,會自動觸發 req 物件的 end 事件,然后就可以在 end 事件中使用接收到的表單 POST 請求體
let datahttps://www.cnblogs.com/ygjzs/p/= ''
req.on('data', chunk => {
data += chunk
})
req.on('end', () => {
// 手動給 req 物件掛載一個 body 屬性,值就是當前表單 POST 請求體物件
// 在后續的處理中間件中,就可以直接使用 req.body 了
// 因為在同一個請求中,流通的都是同一個 req 和 res 物件
req.body = queryString.parse(data)
next()
})
})
// 掛載路由容器(路由容器中組織了網站功能處理路由中間件)
app.use(router)
app.listen(3000, () => {
console.log('server is running at port 3000...')
})
import express from 'express'
// 創建一個路由容器,將所有的路由中間件掛載給路由容器
const router = express.Router()
router.get('/', (req, res, next) => {
res.render('index.html')
})
router.post('/advert/add', (req, res, next) => {
// 介面客戶端提交的資料
console.log(req.body)
})
// 通過 export default 暴露的介面成員不能定義的同時直接暴露
// 最好先定義,再暴露
// export default 可以直接暴露字面量 {} 123
export default router
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/153403.html
標籤:JavaScript
下一篇:nunjucks如何使用?
