1. Complete writing

Let’s take a quick look at how to create a Web server from Node

// import HTTP module let HTTP = require(' HTTP '); // create a server instance object let server = http.createserver (); On ('request', (req, res) => {// end => { Res.end ('sandy'); }) // 4. Specify the listening port server.listen(666);Copy the code

CTRL + Shift +F10 (CTRL + Shift +F10)

Is this server run locally? Is our local server IP address 127.0.0.1? And the port number I listen on is 666

So I can just open 127.0.0.1:666 in my browser

There is another question that is not mentioned, is the data I returned in English? What will happen if I returned in Chinese

// import HTTP module let HTTP = require(' HTTP '); // create a server instance object let server = http.createserver (); On ('request', (req, res) => {// end => { End the request and return data res.end(' Sandy '); }) // 4. Specify the listening port server.listen(666);Copy the code

Is it garbled? Why is it garbled?

Because you’re returning Chinese, you’re not telling the browser what encoding to use to parse the returned content

Knowing why, let’s configure it

Write a status code of 200 to indicate that the request was successful. After success, you can also tell the browser what type of request you returned and how to parse the returned data

// import HTTP module let HTTP = require(' HTTP '); // create a server instance object let server = http.createserver (); On ('request', (req, res) => {// end => { End this request and return data res.writeHead(200, {" content-type ": "text/plain; charset=utf-8" }) // res.end('sandy'); Res. The end (' sandy '); }) // 4. Specify the listening port server.listen(666);Copy the code

Take a look at the browser’s results

2. The abbreviations

let http = require('http'); http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain; Charset =utf-8"}) res.end(' utf-8 '); }).listen(999);Copy the code