一、http
http
The summary of the request is as follows:
DNS
Parsing, establishingTCP
connections, sendinghttp
requestserver
Receiving thehttp
request, the processing, and returns- The client receives the returned data, processes the data, such as rendering the page, and executing
JS
node JS
Processinghttp
the request, as follows:
get
Request andquerystring
post
Request andpostdata
- routing
Two, node JS processes get requests
node JS
Processingget
the request, as follows:
get
Request that the client would likeserver
clients to obtain data such as query list- By
querystring
transmitting data, such asa.html?a=100&b=200
- Direct access to the browser, it sends a
get
request
- By
npm init -y
initializing the project, create a newapp.js
file, the code is as follows:
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
console.log('method:', req.method)
const url = req.url
console.log('url:', url)
req.query = querystring.parse(url.split('?')[1])
console.log('query:',req.query)
res.end(JSON.stringify(req.query))
})
server.listen(8000)
console.log('ok')
- By the
node app.js
command execution program, are input in the browser windowhttp://localhost:8000/api/list
andhttp://localhost:8000/api/list?name=zhangsan&age=20
sendingGET
the request, as follows:
http://localhost:8000/api/list
,as the picture shows:
http://localhost:8000/api/list?name=zhangsan&age=20
,as the picture shows:
Three, node JS processes post requests
node JS
Processingpost
the request, as follows:
post
Request, that is, the client must pass data like the server, such as new information- By
post.data
transmitting data - The browser cannot simulate directly, you need to write by hand
js
, or usepostman
- In the
app.js
document, the code is as follows:
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req,res) => {
if (req.method === 'POST') {
// req 数据格式
console.log('req content-type:', req.headers['content-type'])
// 接收数据
let postData = ''
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
console.log('postData:', postData)
res.end('end 结束')
})
}
})
server.listen(8000)
console.log('ok')
- By
node app.js
command program running inpostman
, thehttp://localhost:8000/
request inraw
the input{ "name": "zhangsan", "age": 24 }
transmissionPOST
request, as shown below: