主要是通过使用NodeJS内置的querystring库处理req.url中的查询字符串来进行
使用NodeJS获取GET请求,主要是通过使用NodeJS内置的querystring库措置惩罚惩罚req.url中的盘问字符串来进行。
通过?将req.url分化成为一个包罗path和query字符串的数组
通过querystring.parse()要领,对格局为key1=value1&key2=value2的盘问字符串进行解析,并将其转换成为标准的JS东西
const http = require(‘http‘) const querystring = require(‘querystring‘) let app = http.createServer((req, res) => { let urlArray = req.url.split(‘?‘) req.query = {} if (urlArray && urlArray.length > 0) { if (urlArray[1]) { req.query = querystring.parse(urlArray[1]) } } res.end( JSON.stringify(req.query) ) }) app.listen(8000, () => { console.log(‘running on 8000‘) })
NodeJS获取POST数据
NodeJS获取POST数据,主要是通过响应req的data事件和end事件来进行
通过req.on(‘data‘),并传入回调函数,响应数据上传的事件,并对数据进行收集
通过req.on(‘end‘),并传入回调函数,,响应数据上传结束的事件,并判断是否存在上传数据。如果存在,就执行后面的逻辑。
// NodeJS获取POST请求 const http = require(‘http‘) let app = http.createServer((req, res) => { let postData = ‘‘ req.on(‘data‘, chunk => { postData += chunk.toString() }) req.on(‘end‘, () => { if (postData) { res.setHeader(‘Content-type‘, ‘application/json‘) res.end(postData) } console.log(JSON.parse(postData)) }) }) app.listen(8000, () => { console.log(‘running on 8000‘) })
get和post合并 const url = require(‘url‘); const http = require(‘http‘); const server = http.createServer((req, res) => { if (req.method === ‘GET‘) { let urlObj = url.parse(req.url, true); res.end(JSON.stringify(urlObj.query)) } else if (req.method === ‘POST‘) { let postData = ‘‘; req.on(‘data‘, chunk => { postData += chunk; }) req.on(‘end‘, () => { console.log(postData) }) res.end(JSON.stringify({ data: ‘请求告成‘, code: 0 })) } }) server.listen(3000, () => { console.log(‘监听3000端?‘) console.log(1111) console.log(22) }
https://www.jianshu.com/p/683894636e72
NodeJS获取GET和POST请求
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30845.html