With this module, we’ll try using TS in Node. Here are the basic steps:

1. Create projects

It’s a familiar process: create an empty directory and open it with WebStorm.

Yarn init -y creates a package.json file. -y is the default value yes.

To create an index.ts file in the directory, run the ts-node-dev index.ts command from the terminal. This will automatically restart the Node program.

You can’t find a Node module in a TS file because node is written in JS. So you need to install the Node declaration file:yarn add --dev @types/nodeThis statement installs all node modules and is a TS declaration. Node_modules node_modules node_modules node_modules node_modules node_modules

2. Index. ts uses HTTP module

It is already possible to introduce HTTP modules in TS.

import * as http from 'http';

const server=http.createServer()

server.on('request'.(request,response) = >{
    console.log('I've been asked.');
    response.end('I'll give you a response')
})

server.listen(8888)
Copy the code

Create a server with HTTP, and that’s a server. We then listen for the server’s request event and execute our callback function whenever someone sends a request to the server. Then start listening for port 8888 on the local machine.

So how do I make a request to this server? You can use the curl command: in our cmder, curl http://localhost:8888 sends a request to port 8888.

In our server, with Node enabled (ts-node-dev index.ts), and the terminal prints’ I was requested ‘. But the CMder is always waiting for a response, and how do we get a response in our server? In this callback, you pass two arguments: Request,response, andResponse.end (' I'll give you a response ')It means to end the request with a response. And then we’ll see that in the CMDER we get this response:

3. Learn more about the HTTP module

1. What is server

What server do we create with http.createserver ()? As you can see from the documentation, this function returns an instance of HTTP.server. Http. Server is a class that creates an object we call Server.

There are many events and methods on this server object, common ones such as the Request event, which is fired whenever there is a request. So we can use on to listen for this request event.

Common methods such as the Listen method are used to start the HTTP server. The listen method must be called once before the server starts.

2. What is request response

In the callback that listens to the request event, two parameters are passed. Constructor or response.constructor:

The request object belongs to the http.IncomingMessage class, so there must also be some properties and methods on the request: for example

Request. httpVersion Indicates the HTTP version sent by the client

Request. method Returns the request method, such as GET and POST

Request. url returns the path to this request

Request. headers returns all request headers as key-value pairs

Use curl to send a requestcurl -v http://localhost:8888/xxx-v displays the content of the request and response. And then print it on the server siderequest.headersThe results are as follows:It can be matched.

Similarly, the Response object belongs to the http.ServerResponse class. What attributes can it use?

Response. statusCode returns the statusCode, which can also be modified

Response.end (‘ give you a response ‘) indicates that the response is complete and must be called. You can also omit the parameter.

Response.write (‘a’) writes the response; The Response object controls everything about the response.

3. How to send POST request (request data event and end event)

Do you want to curl a GET request? If you want to send a POST request, curl -v – d ‘name = anqi http://localhost:8888/xxx using 3-d data back by one. So that’s a POST request.

How does my server get the data sent by the user? How do you get the body of a POST request? The first parameter in the callback, the Request object, contains all the information about the request. This request object has a data event: it will be called if it listens for the user to upload data. So we can listen for its data event, which is used to get the message body.

We know that data is not sent all at once, but in chunks, one at a time. Every time you send a little piece of data, it triggers a data event, so we listen for data events, and we keep getting data. So how do you know when you’re done with the data? There is an end event, which is triggered when no data is available and can be used to concatenate the retrieved data into real data.

const server=http.createServer()
server.on('request'.(request: IncomingMessage,response:ServerResponse) = >{
    console.log('I've been asked.');
    console.log(request.method)
    let array=[]
    request.on('data'.(chunk) = >{
        array.push(chunk)
    })

    request.on('end'.() = >{
        console.log('Data has been sent');
        const requestBody=Buffer.concat(array).toString() // Chunk belongs to Buffer
        console.log(requestBody)
        response.end('I'll give you a response')
    })
})

server.listen(8888)
Copy the code

At this momentresponse.endThe method will be placed in the listener end, because the response cannot be terminated until all data has been received.