
圖片來(lái)源網(wǎng)絡(luò),侵刪
這是在請(qǐng)求正文中提取以 JSON 格式發(fā)送的數(shù)據(jù)的方式。
如果使用的是 Express,則非常簡(jiǎn)單:使用 body-parser Node.js 模塊。
例如,獲取此請(qǐng)求的正文:
const axios = require('axios')
axios.post('http://nodejs.cn/todos', {
todo: '做點(diǎn)事情'
})
這是對(duì)應(yīng)的服務(wù)器端代碼:
const bodyParser = require('body-parser')
app.use(
bodyParser.urlencoded({
extended: true
})
)
app.use(bodyParser.json())
app.post('/todos', (req, res) => {
console.log(req.body.todo)
})
如果不使用 Express 并想在普通的 Node.js 中執(zhí)行此操作,則需要做多一點(diǎn)的工作,因?yàn)?Express 抽象了很多工作。
要理解的關(guān)鍵是,當(dāng)使用 http.createServer() 初始化 HTTP 服務(wù)器時(shí),服務(wù)器會(huì)在獲得所有 HTTP 請(qǐng)求頭(而不是請(qǐng)求正文時(shí))時(shí)調(diào)用回調(diào)。
在連接回調(diào)中傳入的 request 對(duì)象是一個(gè)流。
因此,必須監(jiān)聽要處理的主體內(nèi)容,并且其是按數(shù)據(jù)塊處理的。
首先,通過(guò)監(jiān)聽流的 data 事件來(lái)獲取數(shù)據(jù),然后在數(shù)據(jù)結(jié)束時(shí)調(diào)用一次流的 end 事件:
const server = http.createServer((req, res) => {
// 可以訪問(wèn) HTTP 請(qǐng)求頭
req.on('data', chunk => {
console.log(`可用的數(shù)據(jù)塊: ${chunk}`)
})
req.on('end', () => {
//數(shù)據(jù)結(jié)束
})
})
因此,若要訪問(wèn)數(shù)據(jù)(假設(shè)期望接收到字符串),則必須將其放入數(shù)組中:
const server = http.createServer((req, res) => {
let data = []
req.on('data', chunk => {
data.push(chunk)
})
req.on('end', () => {
JSON.parse(data).todo // '做點(diǎn)事情'
})
})
文章來(lái)源 node中文官方 http://nodejs.cn/
更多知識(shí)點(diǎn) 請(qǐng)關(guān)注:筆墨是小舟