NodeJS获取GET和POST请求

使用NodeJS获取GET请求,主要是通过使用NodeJS内置的querystring库处理req.url中的查询字符串来进行。

  1. 通过?req.url分解成为一个包含pathquery字符串的数组
  2. 通过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数据,主要是通过响应reqdata事件和end事件来进行

  1. 通过req.on(‘data‘),并传入回调函数,响应数据上传的事件,并对数据进行收集
  2. 通过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

相关文章