welcome
Get the HTTP request and response
Something to say
: This article uses node.js code to implement http, mainly to understand the whole process of request and response between browser & curl command and http server. The first part will briefly understand the request and response, and the latter part will systematically learn HTTP. Source code + graphic explanation. --Data source Hungry Man Valley
Precondition
I hope you understand what URL path and query parameters are, and understand IP and port when reading this article. If you don’t know, you can read my http introductory note 1 (analysis of URL) , you need to install Node.js to operate
i. Let's first understand the request and response briefly
-Picture from Hungry Man Valley
-
Request is when the browser in the client sends a request to the server
-
The response is that the server returns a response on the same port after receiving the request
1.1 How to send a request
- ①Use Chrome address bar
The picture below is the first request sent by chrome to www.baidu.com after I entered baidu.com
- ②Use curl command
curl is a commonly used command line tool to request a web server. Its name means the URL tool of the client
Enter in cmder (or cmd) to
curl -v https://www.baidu.com
clearly see the request and response process
After entering the command, you can see that the highlighted part above is the encryption process. The highlighted part is the request sent ('>' part), and the highlighted part is the response returned ('<' part)
You can see that the proxy tool uses curl/7.71.1
Agent tool concept:
The tool that helps you send requests is called [User Agent], the English name is User Agent
1.2 How to make a response
Ask yourself to use curl to send requests and respond to yourself
Node.js has an http module to do it (I also paste and copy the teacher Hungry Guy)
The following is the complete code of the node.js code server, mainly looking at the middle part, the complete code is also available in server.js of https://github.com/woshidw/node-demo1
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]
if(!port){
console.log('请指定端口号好不啦?\nnode server.js 8888 这样不会吗?')
process.exit(1)
}
var server = http.createServer(function(request, response){
var parsedUrl = url.parse(request.url, true)
var pathWithQuery = request.url
var queryString = ''
if(pathWithQuery.indexOf('?') >= 0){
queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
var path = parsedUrl.pathname
var query = parsedUrl.query
var method = request.method
/******** 从这里开始看,上面不要看 ************/
console.log('有个傻子发请求过来啦!路径(带查询参数)为:' + pathWithQuery)
/*每次请求都会执行 */
if(path === '/'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/html;charset=utf-8')
/*响应的描述信息,text/html我是文本,语法是heml*/
response.writ console.log('有个傻子发请求过来啦!路径(带查询参数)为:' + pathWithQuery)
/*每次请求都会执行 */
if(path === '/'){
response.statusCode = 200
/*成功返回状态码200*/
response.setHeader('Content-Type', 'text/html;charset=utf-8')
/*响应的描述信息,text/html我是文本,语法是heml*/
response.write(`
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/x">
</head>
<body>
<h1>如果路径是/,就发送这段内容,格式为html</h1>
<h2>我请求了路径为/x的css
</body>
`)
/* 注意:``和''是不同的,``里可以加回车 ,''里回车用\n表示*/
response.end()
} else if(path === '/x'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/css;charset=utf-8')
response.write(`h2{color: green;}`)
response.end()
} else {
response.statusCode = 404
/*访问的路径不存在返回状态码为404*/
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.write(`你访问的页面不存在`)
response.end()
}e(`
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/x">
</head>
<body>
<h1>如果路径是/,就发送这段内容,格式为html</h1>
<h2>我请求了路径为/x的css
</body>
`)
/*浏览器请求了localhost根目录后,发现根目录要请求一个/x的css,
于是再次发送请求请求/x,这就是html和css通过http传送到浏览器的整个过程,
一个路径返回html字符串,一个路径返回css字符串*/
/* 注意:``和''是不同的,``里可以加回车 ,''里回车用\n表示*/
response.end()
} else if(path === '/x'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/css;charset=utf-8')
response.write(`h2{color: green;}`)
response.end()
} else {
response.statusCode = 404
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.write(`你访问的页面不存在`)
response.end()
}
/******** 代码结束,下面不要看 ************/
})
server.listen(port)
console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)
The response is mainly to discuss the above intermediate code
These codes are server codes, usually on the server
path is the path without query parameters /x
query is the object form of query parameters {a:'1'}
queryString is the string form of the query parameter? a=1
pathWithQuery is a path with query parameters, generally not
request is the request object
response is the response object
1.2.1 Response code logic
① Grammar
-
``You can enter inside
-
''The carriage return can only be expressed by \n
②Logic
- Every time a request is received, the code in the middle will be executed again, the path is judged by if else, and the response will be returned
- If it is a known path, always return 200
- If it is an unknown path, always return 404
- Content-Type represents the "type/syntax" of the content
- response.write() can fill in the returned content
- response.end() indicates that the response can be sent to the user
Enter cd + relative absolute path on the command line to enter the file, enter the following command to display the effect
Follow the link to enter http://localhost:8888 and get the effect
A port 8888 is opened and is monitored by node.js. If someone requests the port 8888, they will enter the node.js code. The above code will be executed every time the server code is changed. The server code must be restarted. Server can take effect
Then look at what the server displays
Click on the address to visit the webpage with path /
ii. Systematic learning of HTTP
2.1 What must be learned
- Basic concepts (mainly request and response)
- How to debug (by using Node.js, log / debugger can be used)
- Where to find information (Node.js is used, see Node.js documentation)
- Who is the standard maker (HTTP specification document: RFC 2612 <RFC 2612 specifically stipulates http rules> etc.)
How to learn (CRM learning method)
- Copy-copy documents, copy teachers
- Run-run successfully on your own machine
- Modify-add a little bit of your own thoughts and rerun
2.2 HTTP basic concepts
1) request
-
Request verb path plus query parameter protocol name/version
-
Host: domain name or IP
-
Accept: text/ html
-
Content-Type: The format of the request body
-
Carriage return (add a carriage return between the request header and the request body to distinguish)
-
Request body (that is, upload content, it can be any content, but it must be clearly written in the request body format)
detail
①. Three parts: request line ( emphasis in red part ), request header (blue part), request body (green part)
②. Request verbs include GET (get content)/POST (upload content) /PUT/PATCH/DELETE, etc.
③. The request body is generally empty in the GET request
④. The document is in Chapter 5 of RFC 2612
⑤. Not case sensitive (optional)
The following figure is the request process
In the developer tools, you can see that the request verb is GET, the access path is / (without query parameters), the protocol is HTTP, and the version number is 1.1
Host is the domain name and port number
Accept is used to indicate what content to accept. The browser will add accept by default to be html or xhtml+xml or xml, etc. (First> HTML first, if there is no HTML, you can also accept Xhtml, if you don’t have Xhtml, you can also accept Xml, etc.)
2) Response
-
Protocol name/version status code status string
-
Content-Type: The format of the response body
-
Carriage return
-
Response body (that is, download content)
detail
①Three parts: status line, response header, response body
②Common status codes are test sites
③The document is in Chapter 6 of RFC 2612
The following figure is the response process
The beginning is HTTP/1.1, protocol plus version. 200 is the status code (200 represents ok), ok is the explanation of 200
Content-Type is the format of the response body (text, syntax is html, character encoding is UTF-8)
You can see the response body in Response. This part of the syntax format is written in Content-Type, as follows
Focus on remembering the request line and status line , HTTP is ok
Remember again:
- The request line is:
Request verb path (plus query parameters) Protocol name/version
- The status line is:
Protocol name/version status code status string
iii. Construct a request with curl
Main codecurl -v http://127.0.0.1:8888
Simple request
- Set request verb
-X POST
curl -v -X POST http://127.0.0.1:8888
You can see that the original GET has become POST
Pay attention to capitalization!!!
- Set path and query parameters
Add directly after the url
curl -v -X POST http://127.0.0.1:8888/xxxx?wd=hi
The path is /xxxx added after the address, and the query parameter is?wd=h1
The anchor will not be passed to the server
- Set request header
-H 'Name: Value’或者–header ‘Name: Value’
curl -v -X POST -H 'Accept: text/html' http://127.0.0.1:8888/xxxx?wd=hi
Change accepting arbitrary to accept html content
Any weird content can be set in the request header, and the server can read it, such as
curl -v -X POST -H 'dw: SB' http://127.0.0.1:8888/xxxx?wd=hi
- Set request body
-d'content' or --data'content'
Usually with POST
Command line input
curl -v -X POST -H 'dw: SB' -H 'Content-Type: text/plain;charset=utf-8' -d '请求体内容' http://127.0.0.1:8888/xxxx?wd=hi
The content I want to upload is plain text, the encoding is utf-8, and the content to be uploaded is the five words "request body content"
Generally 1 Chinese character 2 bytes
iv. Use node.js to read and construct requests
- Read request verb
request.method
console.log('method')
...
console.log('有个傻子发请求过来啦!路径(带查询参数)为:' + pathWithQuery)
/*每次请求都会执行 */
console.log("method:")//method是
console.log(method);//GET或者POST
...
After the server restarts, use curl link curl http://localhost:8888
, the server gets
Use curl to construct verbscurl -X POST http://localhost:8888
- Read path
request.url path with query parameters
After the path is written, the path can be read, so I won’t demonstrate
path is a pure path, without query parameters
query has only query parameters
- Read request header
request.headers[‘Accept’]
...
console.log("request.headers:");
console.log(request.headers);//可以通过request.headers拿到所有的请求头
...
use this curl -v -H 'dw: SB' http://127.0.0.1:8888
Server gets all request headers
- Read request body
v. Set response with node.js
- Set response status code
response.statusCode = 200
You can change the response.statusCode = xxx in node.js to change the status code
...
response.statusCode = 200
/*成功返回状态码200*/
...
- Set the response header
response.setHeader(‘Content-Type’, ‘text/html’);
...
response.setHeader('Content-Type', 'text/htmI');
response.setHeader('dw', 'sb');
...
You can modify the response header through the above part
- Set response body
response.write(‘内容’)
Can add content
response.write(`
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/x">
</head>
`)
response.write(`
<body>
<h1>如果路径是/,就发送这段内容,格式为html</h1>
<h2>我请求了路径为/x的css
</body>
`)
The first time I wrote the head, the second time I wrote the body, you can add content, as follows, you can read it all
--continue
I am on my way to learn the front end from entry to soil. Every time you watch, it is your greatest encouragement to my learning journey, let's work hard together!
Welcome to leave your valuable comments.
In the end, you may be tired, send a wave of benefits
-The picture comes from the Internet