1、请求GET处理
querystring是用来处理Get的参数请求的
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const method = req.method
const url = req.url
const path = url.split('?')[0]
const query = querystring.parse(url.split('?')[1])
// 设置返回格式为JSON
res.setHeader('Content-type', 'application/json')
// 返回的数据
const resData = {
method,
url,
path,
query
}
// 返回
if(method === 'GET') {
res.end(
JSON.stringify(resData)
)
}
})
server.listen(3000, () => {
console.log('ok')
})
2、处理POST请求
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const method = req.method
const url = req.url
const path = url.split('?')[0]
const query = querystring.parse(url.split('?')[1])
// 设置返回格式为JSON
res.setHeader('Content-type', 'application/json')
// 返回的数据
const resData = {
method,
url,
path,
query
}
// Get请求处理
if(method === 'GET') {
res.end(
JSON.stringify(resData)
)
}
// Post请求处理
if(method === 'POST') {
let postData = ''
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
resData.postData = postData
// 返回
res.end(
JSON.stringify(resData)
)
})
}
})
server.listen(3000, () => {
console.log('ok')
})