把今天學到的東西記錄一下
const http = require('http')
// querystring 模塊提供用於解析和格式化 URL 查詢字符串的實用工具
const querystring = require('querystring')
const server = http.createServer((req, res) => {
// 請求的方式
let method = req.method
console.log('method :', method)
// 0.如果是Post請求
if (method === 'POST'){
// 數據格式
contentType = req.headers['content-type']
console.log('content-type:',contentType)
// 接收數據
let postData = ''
// chunk爲一點點數據,逐漸積累
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
console.log('postData:', postData)
// 在這裏返回 因爲是異步
res.end('hello world')
})
}
// 1. 如果是get請求
if (method === 'GET'){
// 獲取完整請求url
const url = req.url
// 解析 get請求的參數 爲?後面 所以數組下標爲1
req.query = querystring.parse(url.split('?')[1])
// 返回
res.end(
// 返回json字字符串
JSON.stringify(req.query)
)
}
})
server.listen(8000)