- 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 作为测试。