Handle HTTP requests and responses


Have to say

HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP HTTP — Source: Hungry Man Valley


precondition

I hope you understand what URL paths and query parameters are, and understand IP and port when you read this article. If you don’t know, take a look at my Introduction to HTTP note 1. To do this, install Node.js

I. Let’s take a quick look at requests and responses

— Image from Hungry Man Valley

  • A request is when the browser in the client sends a request to the server

  • A response is when the server receives the request and returns a response on the same port

1.1 How do I Send a Request

  • ① Use the Chrome address bar

Below is the first request chrome sent to www.baidu.com after I typed baidu.com

  • ② Use curl command

Curl is a common command-line tool used to request Web servers. Its name stands for client’s URL utility

Enter curl -v https://www.baidu.com into cmder(or CMD) to see the request and response process

When you enter the command, you can see that the encryption process is highlighted above, the request sent (‘>’) is highlighted below, and the response returned (‘<‘) is highlighted below.

You can see that the agent tool uses curl/7.71.1

Proxy tool concepts:

The tool that makes the request for you is called User Agent

1.2 How to make a response

Use curl to send a request for a response

Node.js has an HTTP module to do this.

Here is the complete node.js code server code, mainly look at the middle section, the complete code at github.com/woshidw/nod… It’s also in server.js

var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(! port){console.log('Please specify a port number, ok? \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

  /******** start here, don't look at ************/ above
   console.log('Some idiot sent me a request! The path (with query parameters) is: ' + pathWithQuery)
/* Each request is executed */
  if(path === '/'){
    response.statusCode = 200
    response.setHeader('Content-Type'.'text/html; charset=utf-8')
    /* Description of the response, text/ HTML I am the text, syntax is heml*/
    response.writ  console.log('Some idiot sent me a request! The path (with query parameters) is: ' + pathWithQuery)
/* Each request is executed */
  if(path === '/'){
    response.statusCode = 200
    /* Successful return status code 200*/
    response.setHeader('Content-Type'.'text/html; charset=utf-8')
    /* Description of the response, text/ HTML I am the text, syntax is heml*/
    response.write(` 
        
         

The format is HTML

I requested CSS 'with path /x

) /* Note: '' and '' are different, '' can be used to return the car, '' \n for */ 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 /* The accessed path does not exist. The return status code is 404*/ response.setHeader('Content-Type'.'text/html; charset=utf-8') response.write(The page you visited does not exist) response.end() }e(`

The format is HTML

I requested CSS 'with path /x

) /* The browser requests the localhost root directory and finds that the root directory requests a CSS /x, so it sends a request /x again. This is how the HTML and CSS are sent to the browser via HTTP. One path returns the HTML string, and the other path returns the CSS string */ /* Note: '' and '' are different, '' can be used to return the car, '' \n for */ 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(The page you visited does not exist) response.end() } /******** code ends, do not read ************/ }) server.listen(port) console.log('listen' + port + 'Success \n Please turn 720 degrees in the air and then open http://localhost:' with the rice cooker. + port) Copy the code

The response mainly revolves around the above intermediate code to discuss

  • This code is the server code and is generally placed on the server

  • Path is the path /x without query parameters

  • Query is the object form of the query parameter {a:’1′}

  • QueryString is a string form of a query parameter, okay? a=1

  • PathWithQuery is a pathWithQuery parameters

  • Request is the request object

  • Response is the response object

1.2.1 Code logic of response

(1) grammar

  • You can enter in there

  • The carriage return in ‘ ‘can only be denoted by \n

(2) the logic

  • Every time I get a request, I’m going to go through the code in the middle and I’m going to say if else and I’m going to return a response
  • If it’s a known path, always return 200
  • If the path is unknown, 404 is returned
  • Content-type indicates 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

Run the CD + related absolute path command to go to the file. The command output is as follows

Follow the link to enterThe effect obtained after http://localhost:8888

Node.js has a port 8888 on it, which is monitored by Node.js. If someone requests port 8888, it will enter node.js code, and execute the above code for each request

And then what does the server show

Click the address to visit the page with path /


Ii. Systematic learning of HTTP

2.1 What must be learned

  • Basic concepts (mainly requests and responses)
  • How to debug (with Node.js, you can use log/debugger)
  • Where to find information (using Node.js, see the Node.js documentation)
  • Who is the standard maker (HTTP specification document :RFC 2612

    etc.)

How to Learn (CRM Learning Method)

  • Copy- Copy a document, Copy a teacher
  • Run – Run successfully on your own machine
  • Modify – Add a bit of your own ideas and run again

2.2 Basic CONCEPTS of HTTP

1) request

  • Request verb path plus query parameter protocol name/version

  • Host: indicates the domain name or IP address

  • Accept: text/ html

  • Content-type: specifies the format of the request body

  • Carriage return (request header and request body separated by carriage return)

  • Request body(That is, upload content, can be any content, but make it clear in the request form)

details

①. Three parts: request line (red part key), request header (blue part), request body (green part)

GET /POST /PUT/PATCH/DELETE

③ The request body is usually empty in a GET request

④ Documentation is located in Chapter 5 of RFC 2612

⑤. Case insensitive (optional)

Below is the request process

In 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 you want to Accept. The browser defaults to Accept: HTML, XHTML + XML, XML, etc.

2) response

  • Protocol name/Version status code Status character string

  • Content-type: indicates the format of the response body

  • enter

  • Response body(Download content)

details

① Three parts: status line, response header, response body

② The most common status code is the test point

③ Documentation is located in Section 6 of RFC 2612

Below is the response process

It starts with HTTP/1.1, protocol plus version. 200 is the status code (200 stands for OK). Ok is the description of 200

Content-type is the format of the response body (text, HTML syntax, utF-8 character encoding).

In Response, you can see the Response body. The syntax format of this part is written in content-Type, as follows

Keep in mind the request line and the status line, and HTTP is fine

Remember it again:

  • The request line is:

Request verb path (plus query parameters) protocol name/version

  • The status line is:

Protocol name/Version status code Status character string


Use curl to construct a request

Main code curl -v http://127.0.0.1:8888

Simple Request

  • Set the request verb

-X POST

Curl - V-x POST http://127.0.0.1:8888

And you can see that GET becomes POST

Pay attention to case!!

  • Set paths and query parameters

Add it directly after the URL

The curl -v - X POST at http://127.0.0.1:8888/xxxx? wd=hi

After the address, the path is/XXXX, and the query parameter is? Wd =h1, the anchor is not going to the server

  • Set the request header

-h ‘Name: Value’ or –header ‘Name: Value’

The curl -v - POST - H X 'Accept: text/HTML' http://127.0.0.1:8888/xxxx? wd=hi

Changed accept arbitrary to accept HTML content

Request header here can set any strange content, the server can be read, such as curl -v – POST – H X ‘dw: SB’ http://127.0.0.1:8888/xxxx? wd=hi

  • Set the request body

-d ‘contents’ or –data’ contents’

Usually with POST

Curl -v -x POST -h ‘dw: SB’ -h ‘Content-type: text/plain; Charset = utf-8 ‘3-d’ request body content ‘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 I want to upload is’ request body content ‘

Generally, one Chinese character has two bytes


Iv. Construct request with Node.js read

  • Read request verb

request.method

console.log('method')

.console.log('Some idiot sent me a request! The path (with query parameters) is: ' + pathWithQuery)
/* Each request is executed */
console.log("method:")/ / method is
console.log(method);/ / the GET or POST.Copy the code

After the server restarts, use the curl link curl http://localhost:8888 to get the server

Curl curl -X POST http://localhost:8888

  • Read the path

Request. url path with query parameters

After the path is written, the path can be read, not demonstrated

Path Indicates 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);// You can get all the headers from request.headers.Copy the code

Use this curl – V-h ‘dw: SB’ http://127.0.0.1:8888

The server gets all the request headers

  • Read request body

V. Set the response with Node.js

  • Set the response status code

response.statusCode = 200

Node.js response.statuscode = XXX to change the statusCode

. response.statusCode =200
 /* Successful return status code 200*/.Copy the code
  • Setting the response header

response.setHeader(‘Content-Type’, ‘text/html’);

. response.setHeader('Content-Type'.'text/htmI');
response.setHeader('dw'.'sb'); .Copy the code

You can modify the response header through the above section

  • Set the response body

Response. Write (‘ content ‘)

Append content

response.write(` 
        
        `)
    response.write(' 

If the path is /, send this content in HTML

I requested CSS ' with path /x

) Copy the code

The first time I’m going to say head, the second time I’m going to say body, and I can append something like this, so I can read it












Learning the front end from the beginning to the ground, I’m on my way. Every time you watch, is the biggest encouragement on my way to study, work hard together!

Welcome to leave your valuable comments.

Finally, you may be tired of watching, send a wave of benefits

— Pictures from the Internet