Tools installation

Installation tool ts-node-dev

This tool can be used to develop Node.js applications in TypeScript and restarts automatically. It’s not suitable for production use, but it’s great for learning

yarn global add ts-node-dev
Copy the code

The curl command

// GET curl -v url // POST curl -v -d "name=ade" http://localhost:8888/Copy the code

Build the project

  • yarn init -y
  • A new index. Ts
  • Start using the command line or WebStorm
  • Yarn add — dev@types /node Installs the node declaration file
  • Import HTTP module (WebStorm automatic import)
  • Create server with HTTP (WebStorm name automatically)
  • Listen for server request events (shorthand)
  • Server. listen(8888) Starts listening on port 8888
  • usecurl -V http://localhost:8888Send the request

Start the application

ts-node-dev index.ts
Copy the code

What is the server

First we see [the] Chinese documents (HTTP | Node. Js API documentation (nodejs. Cn))

http.createServer([options][, requestListener])
Copy the code

Server is an instance of the http. server class and inherits the Net. server class, which returns a new:

instance.

There are important classes for IncomingMessage and ServerResponse in Option.

The IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the ‘Request’ and ‘Response’ events, respectively. It can be used to access response status, headers, and data.

ServerResponse This object is created internally by the HTTP server, not by the user. It is passed as the second argument to the ‘request’ event.

The serve is widely used

Server.listen () : Starts the HTTP server to listen for connections.

server.listen(7777); // Listen on port 7777Copy the code

innet.ServerThere are several heavily used events in the class

‘error’ event: Emitted when an error occurs. The ‘close’ event will not continue to fire after this event unless server.close() is called manually.

A GET request

  • Request. method Gets the request verb
  • Request. url To obtain the request path (including query parameters)
  • Request. header Gets the request header
  • Get requests generally do not have a message body/request body

A POST request

The data and end events inherit from the Stream.Readable class, associated documentation

Request.on (‘data’,fn) gets the message body, which is triggered when the stream passes the data block to the consumer.

const readable = getReadableStreamSomehow(); Readable. on('data', (chunk) => {console.log(' received ${chunk.length} bytes of data'); });Copy the code

Request. on(‘end’,fn) concatenates the message body, triggered when there is no data in the stream to consume.

const readable = getReadableStreamSomehow(); Readable. on('data', (chunk) => {console.log(' received ${chunk.length} bytes of data'); }); Readable.on ('end', () => {console.log(' no data left '); });Copy the code

The request, what is the response

Request is an instance of HTTP. IncomingMessage, which can be used to access response status, headers, and data, which in layman’s terms is all information about the request.

According to the document

Have headers, Method, URL, and other attributes

Request.method () // Request path request.url()Copy the code

The stream.Readable class inherits data/ End /error events

ServerResponse is an instance of http.ServerResponse, which in layman’s terms is all the information in the response.

According to the document

Have getHeader/setHeader/end/write method

// This property controls the status code to be sent to the client when the response header is refreshed. response.statusCode = 404; // Sets the value of a single response header for the implicit response header. response.setHeader('Content-Type', 'text/html'); // This will send a response body. This method can be called multiple times to provide contiguous fragments of the response body. Response.write () // This method signals to the server that all response headers and bodies have been sent and that the server should consider the message complete. This response.end() method must be called on each response. response.end('xxx');Copy the code

Has the statusCode attribute, can read and write

Stream is not currently used

A little of actual combat

Match any file

Const {pathname, search} = url.parse(path); let fileName = pathname.substr(1); Fs. readFile(p.resolve(publicDir, fileName), ()=>{})Copy the code

Set the home page

let fileName = pathname.substr(1); if (fileName === '') { fileName = 'index.html'; }Copy the code

Non-get request Settings

if (method ! == 'GET') { response.statusCode = 405; response.end(); return; }Copy the code

Set the cache

Cache-control A generic header field used to specify directives to implement caching in HTTP requests and responses.

MDN related documents

response.setHeader('Cache-Control', 'public, max-age=31536000'); response.end(data);Copy the code