The guide

  • Installation Node. Js 8 +
  • Understand IP and port
  • Understand URL paths and query parameters

Demo Node.js Server ⭐

Request and response model

  • A server is a computer without a monitor

How to Send a request

methods

  • Use the Chrome address bar
  • Use the curl command

concept

  • The tool that makes the request for you is called a user agent
    • If you use the Chrome address bar to send a request, Chrome is our “user agent.”
    • If you use curl to send a request, curl is your “user agent.”
  • The User Agent name is User Agent

How to make a response ⭐

To make a request, use the Chrome address bar or curl command

  • So how do you make a response? (Demonstrate the process of sending your own request – your own response)

You need programming

  • Node.js has an HTTP module that does this

  • Create the project directory node-demo/server.js and paste the following code into ⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

    Regardless of the code details, directly copy the use. (Note that the purpose of this piece is not to learn NodeJS, but to understand HTTP requests and responses)

    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)
    
      if (path === '/') {
        response.statusCode = 200
        response.setHeader('Content-Type'.'text/html; charset=utf-8')
        response.write(Two ha ` `)
        response.end()
      } else if (path === '/x') {
        response.statusCode = 200
        response.setHeader('Content-Type'.'text/css; charset=utf-8')
        response.write(`body{color: red; } `)
        response.end()
      } else {
        response.statusCode = 404
        response.setHeader('Content-Type'.'text/html; charset=utf-8')
        response.write('The path you entered does not have the corresponding content')
        response.end()
      }
    
      /******** code ends, do not read ************/
    })
    
    server.listen(port)
    console.log('listen' + port + 'Success \n Please turn 720 degrees in the air and open http://localhost:' with the rice cooker. + port)
    Copy the code

Matters needing attention

  • 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
  • \n indicates enter

Operation mechanism ⭐

  1. Starting an application on a terminal:

    1. runnode server.jsIs not specifiedThe port number, there will be a hint
    2. Follow the instructionsnode server.js 8888ornode server 8888This means that our computer will open port 8888, which is listened on by server.js
    3. At this point, as soon as someone requests port 8888, it will walk into server.js code, and our annotated code will run again. Run each time a request is received
  2. Use the curl request curl http://127.0.0.1:8080/xxxx. Server.js receives the request and responds.

    • If the response content is garbled, the fault may be caused by the Windows operating system
  3. Add the routing

    1. Edit the server.js file to add if else (conditional, access a path, response)

    2. Re-run Node server.js 8888 (restart required to modify service code)

      if (path === '/') {
        console.log('Someone called/')
        response.end('That's what the access/response is for \n')   / / enter \ n
      } 
      Copy the code

      Here is the console.log(…) that server.js executes when listening for the curl command to request the root path.

  4. Background startup application:

    1. Touch log Creates a log file

    2. node server.js 8888 >log log 2>&1 &

      The returned number 1144 is the ID of the process (currently running in the background).

    • After running, the server starts in the background and does not occupy the current terminal
    • How do I close this background process?
      • performkill -9 xxxxXXXX is the ID of the background process
      • Kill-9 is the most powerful way to kill a process

Code logic

grammar

'Such a stringI can enter'Such a string'The carriage return inside can only be denoted by \nCopy the code

logic

  1. The intermediate code is executed every time a request is received

  2. Use if else to determine the path and return the response

  3. If it’s a known path, always return 200

  4. If the path is unknown, 404 is returned

  5. Content-type indicates the “Type/syntax” of Content (omits the suffix, which programmers never read 😎, and which simply tells computers what software to use to open a file)

    `text/html`,`text/css`Path is written /x instead of /x. CSS, because the type/syntax is already declared in the content-Type, so the suffix.css can be omittedCopy the code
  6. Response.write () can fill in the returned content (write the response content)

  7. Calling response.end() means the response is ready to be sent to the user (calling response.end() sends the response to the browser)

    (Before not write end will wait for a long time, now may be optimized can not write end, for the sake of rigor or write complete, explicitly inform the response to the user)

     if (path === '/') {
        response.statusCode = 200
        response.write(` 
             < head > < meta charset = "utf-8" > < link rel = "stylesheet" href = "/ x" > / / < < < < < < < < < < < < < < < < < < combine HTML and CSS   

    Title

    '
    ) response.end() } else if (path === '/x') { response.statusCode = 200 response.setHeader('Content-Type'.'text/css; charset=utf-8') response.write(`body{color: red; } `) response.end() } Copy the code

    • This is the whole process of linking HTML and CSS to a web page via HTTP: one path returns the HTML string and the other responds to the CSS string.

    • This is Sir Lee’s invention of URL + HTTP + HTML

Notice the sign ‘ ‘

Backquotes recognize carriage returns and syntax

The single quote ‘ ‘does not recognize carriage return syntax and is used only as a string

Think of Sir Lee

The world’s first server program

  • Let’s also write a server program

The world’s first web page

  • We return an HTML content in the/path

  • It then returns a CSS content in the /x path

  • Then the /y path returns a JS content

     if (path === '/') {
        response.statusCode = 200
        response.write(` 
             < head > < meta charset = "utf-8" > < link rel = "stylesheet" href = "/ x" > please please please please please please please please please please please please please please introduce CSS < / head > < body > < h1 > title < / h1 > < script SRC = "/ y" > < script > please please please please please please please please please please please please please please please introduce js < / body > `)
        response.end()
      } else if (path === '/x') {
        response.statusCode = 200
        response.setHeader('Content-Type'.'text/css; charset=utf-8')
        response.write(`body{color: red; } `)
        response.end()
      } else if(path === "/y"){
        response.statusCode = 200;
        response.setHeader("Content-Type"."text/javascript; charset=utf-8");
        response.write('console.log(' This is the JS content ')';
        response.end();
      } else {
        response.statusCode = 404;
     		response.setHeader('Content-Type'.'text/html; charset=utf-8')
        response.write('The path you entered does not have the corresponding content')
        response.end()
      }
    Copy the code

Matters needing attention

  • About the suffix
    • Even if the writtenpath === "/y.css", but if the content-Type specifies a JS Type, it will be resolved as JS. Therefore, the CSS suffix in the URL is useless
    • The content-type is what determines the file Type

Systematize learning HTTP

What you must Learn

  • Basic concepts (which are required)
    • Request and response
  • How to debug (using Node.js, using log/debugger)
    • The essence is to learn HTTP, so don’t spend too much time on Nodejs, just understand how to debug Nodejs
  • Where to find information (node.js is used, so see the Node.js documentation)
  • Who is the standard maker (HTTP specification document: RFC2616 (Chinese) etc.)

How to learn

  • 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

HTTP Basic Concepts

  • You must click view Source to see the complete request and response

request

  • Request verb path plus query parameter protocol name/version(All requests follow this format, simplified version) example:GET /x? Wd = hi HTTP / 1.1
  • Host: is the domain name or IP address (including port number).

  • Accept: text/ HTML (indicates what the browser wants to Accept)

    • Test: Returns different content according to Accept

      var accept = request.headers['accept'];  // Get the value of Accept in the request header and assign it to the variable
      if(accept.indexOf('xml')){
        response.write('I know you want to access XML content')}else{
        response.write(` 
                ... `)}Copy the code
    • What the browser accepts: Accept. (For the most part, browsers just accept HTML.)

      The default is to find HTML first. If you don’t have HTML, you can take XHTML, XML, webp, PNG, and inion-Exchange.

      Accept:text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b3; q=0.Copy the code
  • Content-type: indicates the format of the request body (for example, text/javascript; Charset = utf-8)

  • Carriage return (demarcation of header and body)

  • Request body (that is, upload content)

details

  • The request has three parts, separated by carriage returns, which are :(color corresponding to ↑)

    • Request line (called request line because there is only one line)GET /x? Wd = hi HTTP / 1.1
    • Request header
    • Request body (the format of the request body is specified in the Content-Type)
  • Request verbs include GET, POST, PUT, PATCH, and DELETE

    • GET is used to GET content

    • POST Is used to upload content

      Send a post request: curl-v-x post --data 'upload content' http://localhost:8888/Copy the code

  • The request body is generally empty in a GET request

    • Because GET requests are usually used to get content, and the request body represents the content to be uploaded, GET requests generally do not have a request body
  • The documentation is in chapter 5 of RFC2616

  • Case insensitive (optional), best to follow my writing

The response

  • Protocol name/Version status code Status character string
  • Content-type: indicates the format of the response body
  • enter
  • Response body (that is, downloaded content)

details

  • The response has three parts, separated by carriage returns:
    • Status LIne
    • Response headers
    • Response body (the format of the response body, specified in content-Type)
  • The common status code isThe examination site
    • 200 success
    • 404 can’t find
  • The documentation is in chapter 6 of RFC2616

Construct the request with curl

The curl usage

Curl curl curl curl curl curl curl curl curl curl curl curl

  • You can change anything, you can ask for anything you want
  • You just need to write it according to HTTP standards

The server must be enabled: node server.js 8888

Example: curl -v http://localhost:8888

Set the request verb

  • -X POST
  • Example: curl -v -X POST http://localhost:8888 Set the request to POST
  • Pay attention to case

Set paths and query parameters

  • Add it directly after the URL
  • Example: the curl -v – X POST at http://localhost:8888/xxx? id=xxx
  • Note: adding a # anchor to the URL will not be sent to the server

Set the request header

  • -H 'Name: Value' or--header 'Name: Value'
  • Example: curl – v-x post-h ‘Accept: text/ HTML ‘http://localhost:8888

Set the request body

  • -d 'contents'or--data 'contents'
  • curl -v -X POST -H 'ABC: abc' -H 'Content-Type: text/plain; Charset = utF-8 '-d' Request body content 'http://localhost:8888

    Set an ABC: ABC in the request body, which has no practical meaning but is valid.

    Text /plain indicates that the uploaded content is plain text, the encoding is utf-8 (Chinese), and the content is’ request body content ‘(each word contains 2bytes).

You can use curl to make a request

Read the request with Node.js

Read request verb

  • request.method

    console.log('method:', request.method)   // method: GET ...
    Copy the code

Read the path

  • Request. url path with query parameters

    console.log('Path:', request.url) // Path: / XXXX? wd=hihihi
    Copy the code
  • Path Indicates a pure path without query parameters

  • Query Has only query parameters

Read request header

  • ** Request. Headers [‘Accept’] ** Reads the Accept value in the request header

    console.log("Request header:", request.headers)  {host: XXX,??? :????? . }
    Copy the code

Read request body

  • It’s a little bit complicated, so I’m not going to talk about it

Set the response with Node.js

Set the response status code

  • response.statusCode = 200
  • The status code can be set arbitrarily, and the status string automatically changes according to the status code
  • However, there are uniform rules for the use of status codes. For example, the 200 rule is the status code returned when a request is successful, so do not change it at will
  • 404 indicates that the requested page does not exist. A 404 page is a normal page, provided by Chrome, that alerts the user when the page doesn’t exist

Setting the response header

  • response.setHeader("Content-Type", "text/html");

Set the response body

  • Response.write (" content ")

  • Append content

What does Curl do

Not just for testing HTTP requests and responses.

Curl does most of Chrome’s basic functions, but it doesn’t have visual capabilities because it works from the command line

  1. Download the pictures

    JPG > xxx.jpg (in the command line open directory, download the image and rename it XXX)

    curl https://i.loli.net/2020/07/15/Q2dnHSgxCcbfhZW.jpg > 3.jpg
    Copy the code

  2. Test the request and response

  3. Curl is powerful enough that you can do all of Chrome’s basic functions without visualization

HTML/CSS/JS are essentially strings

HTML/CSS/JS are essentially strings, not files

  • In essence, we see web pages rendered by HTML strings, which request CSS strings, JS strings
  • You can see this in the demo server.js

Console. log Debugging method

Console. log is a debugging method that works in all programming languages

JS (console.log), Java (print), Python (print), PHP (echo)… Different language/writing, but same principle

  • Print out any code that might be problematic
  • Debug is the process of constantly questioning yourself
  • Don’t trust yourself too much, but trust console.log() to tell you right from wrong
  • Every day programmers ask themselves what went wrong