- nodejs处理http请求
- http请求概述
- DNS解析,建立TCP连接(3次握手),发送http请求。
- 3次握手:A: Are you OK? B: Yes, you can connect me anytime. A: okay, I got it, I'm ready to connect you.
- server端接收到http请求,处理,并返回。
- get请求,主要是通过querystring来传递参数,如.../index.html?a=2&b=3
- 客户端接收到返回数据,处理数据(如渲染页面,执行js等)
- DNS解析,建立TCP连接(3次握手),发送http请求。
- http请求概述
- 搭建开发环境
- 开发接口(暂不连接数据库,暂不考虑登录,可以返回一些假数据等)
get请求代码示意
const http = require('http') const querystring = require('querystring') const server = http.createServer((req, res) => { console.log('req method: ',req.method) //GET const url = req.url console.log('url: ', req.url) // /api/test.html?a=1&b=2&c=10 req.query = querystring.parse(url.split('?')[1]) console.log('req query: ', req.query) //[Object: null prototype] { a: '1', b: '2', c: '10' } res.end(JSON.stringify(req.query)) // 如果不用JSON.stringify处理,直接使用会报错。 // res.end(req.query) }) server.listen(8000)
成功运行后,可以在浏览器输入:http:localhost:8000/api/test.html?a=1&b=2&c=10 作为测试。
post请求代码示意:
const http = require('http'); const server = http.createServer((req, res) => { if (req.method == 'POST'){ console.log('content-type: ', req.headers['content-type']) let postData = '' // chunk是数据块的意思,post数据有的很大,有的很小。 // 抽象层面传输按类似水流的方式,积少成多的把数据一点点传完. // chunk一般为二进制,所以示例中用 chunk.toString的方法转换成字符串的形式 req.on('data', chunk => { postData += chunk.toString() }) req.on('end', () => { console.log('postData: ', postData) res.end('hello world!') }) } }) server.listen(8000) console.log('server is running.')
在终端中用node运行这个文件,会打印server is running.
POST请求,可以用代码或者浏览器请求,这里用PostMan比较方便,可直接下载PostMan的客户端或者chrome的插件。
当用PostMan发送如下图数据:
终端中也返回了一些数据,如图: