多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] >[success] # 处理http请求的综合示例 在上两章里面讲解了 **nodejs** 如何处理接收到的 **post请求** 与 **get请求** 的数据,之前还遗漏了一个点,就是后端 **response** 给前端 **返回数据时候,可以指定返回数据的格式** ,那么接下来在下面代码中演示一下: ~~~ // 引入node自带的http模块 const http = require('http') // 引入querystring模块 const querystring = require('querystring') // 通过http创建服务 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( // 这里返回的是字符串,但是浏览器只知道你是字符串并不知道你这个字符串的类型最终是html还是json,所以上面需要告诉浏览器我返回的字符串类型是json JSON.stringify(resData) ) } if(method === 'POST'){ let postData = '' req.on('data', chunk => { postData += chunk.toString() }) req.on('end', () => { resData.postData = postData res.end( // 这里返回的是字符串,但是浏览器只知道你是字符串并不知道你这个字符串的类型最终是html还是json,所以上面需要告诉浏览器我返回的字符串类型是json JSON.stringify(resData) ) }) } }) // 监听3000端口 server.listen(8001) ~~~ 上面的代码中设置了 `res.setHeader('Content-type', 'application/json')` 这段代码,意思是 **服务端告诉浏览器** 我返回的格式是 **json** 格式,而并非是简单的 **字符串格式**。