1、http-get
const http = require('http');
const querystring = require('querystring')
const server = http.createServer((req,res)=>{
const url = req.url;
req.query = querystring.parse(url.split('?')[1])
res.end(
JSON.stringify(req.query)
)
})
server.listen(8000,()=>{
console.log('server is linstening at 8000 port')
})
//NODE控制台返回结果:
// GET
// url: /api/get?user=weibin&age=18
// query: { user: 'weibin', age: '18' }
// GET
// url: /favicon.ico
// query: {}
2、http-post
//使用POSTMAN 模拟请求 选择POST方式 填写JSON 访问http://localhost:8100
const http = require('http')
const server = http.createServer((req,res)=>{
if(req.method === 'POST') {
console.log('req content-type',req.headers['content-type']) //JSON
let postData = ''
// 一点一点接受数据 然后拼接起来
req.on('data',chunk=>{
console.log('first', chunk.toString());
postData += chunk.toString()
})
// 接受完毕触发req的END
req.on('end',()=>{
console.log('postData: ' + postData)
res.end('hello world')
})
}
})
server.listen(8100,()=>{
console.log('server is linstening at 8100 port')
})
3、get、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
}
//返回结果
if (method === 'GET') {
res.end(JSON.stringify(resData))
}
if (method === 'POST') {
let postData = ''
// 一点一点接受数据 然后拼接起来
req.on('data', chunk => {
postData += chunk.toString()
})
// 接受完毕触发req的END
req.on('end', () => {
resData.postData = postData
res.end(JSON.stringify(resData))
})
}
})
server.listen(8000, () => {
console.log('server is linstening at 8000 port')
})