` –

List of topics: juejin, github, smartblue, cyanosis, channing-cyan, fancy, hydrogen, condensed-night-purple, greenwillow, v-green, vue-pro, healer-readable, mk-cute, jzman, geek-black, awesome-green

Contribution Subject:Github.com/xitu/juejin…

theme: juejin highlight:

The previous article gave you an overview of the HTTP module’s basic framework. Take a closer look:

1. How do I request different files based on different URLS

This is our current directory structure. The three files in public need to be requested. And HTML references CSS and JS.

import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';
import * as fs from 'fs';
import * as path from 'path';
import * as url from 'url';

const server=http.createServer()

server.on('request'.(request: IncomingMessage,response:ServerResponse) = >{
    const publicDir=path.resolve(__dirname,'public')
    const {url:myUrl}=request
    console.log(myUrl);
    const {pathname}=url.parse(myUrl)

    switch(pathname){
        case '/index.html':
            response.setHeader('Content-Type'.'text/html; charset=utf-8')
            fs.readFile(path.resolve(publicDir,'index.html'),(err,data) = >{
                if(err) throw err;
                response.end(data.toString())
            })
            break;
        case '/style.css':
            response.setHeader('Content-Type'.'text/css; charset=utf-8')
            fs.readFile(path.resolve(publicDir,'style.css'),(err,data) = >{
                if(err) throw err;
                response.end(data.toString())
            })
            break;
        case '/main.js':
            response.setHeader('Content-Type'.'text/javascript; charset=utf-8')
            fs.readFile(path.resolve(publicDir,'main.js'),(err,data) = >{
                if(err) throw err;
                response.end(data.toString())
            })
            break;
        default:
            response.statusCode=404
            response.end('Not Found')
    }
})

server.listen(8888)
Copy the code

Of course, you must first listen for the server’s request event. In the callback, you can use the URL property of the request object to obtain the requested path. For example if I enter http://localhost:8888/index.html that the request to the browser. The url = = = / index. The HTML so through judging condition request. It returns different url points file contents:

  1. First of all, the types of files vary, throughresponse.setHeaderSet the file type.
  2. How do you get the contents of a file and respond back? First, read the contents of the file: another module is used herefsFile module.fs.readFileThe first argument is the file path, and the second argument is the callback: accepts err and data, which is of type buffer. So we got the files and used themresponse.endTo return.

The FS module is the file system and is used to interact with the file system.

Another module, PATH, is used to find paths for files and directories. Path.resolve () is used to merge multiple path sequences into absolute paths. Resolve is convenient because we are not sure whether paths are joined with/or \.

In the node__dirnameThe variable represents the absolute path to the directory where the current file is located

2. What if there are query parameters in the request URL

If I enter http://localhost:8888/index.html that the request to the browser. The url = = = / index. The HTML that is no problem. But what if I bring query parameters? http://localhost:8888/index.html?age=18 found that request at this time. The url = = = / index HTML? Age = 18 how access to clean pure file path?

The URL module is used: for processing and parsing urls

url.parse(myUrl)MyUrl is request.url, which is just/index.html? age=18Such a string. Get an object: you can see that this object has apathnameProperties, that’s what we want

3. Webstorm sets the directory as the root directory

This is the current directory structure. A 404.html is written as a 404 page that displays the requested path when it does not exist. In 404.html, an image is used:

<body>
    <h1>The page you are looking for does not exist</h1>
    <p>
        <img src="./images/404.png" alt="">
    </p>
</body>
Copy the code

Set the SRC property using a relative path.

// index.ts
fs.readFile(path.resolve(publicDir,filename),(err,data) = >{
        if(err){
            if(err.errno===-4058){
                response.statusCode=404
                fs.readFile(path.resolve(publicDir,'404.html'),(err,data) = >{
                    response.end(data)
                })
            }else{
                response.statusCode=500
                response.end('Server busy')}}else{
            response.end(data)
        }
    })
Copy the code

In node’s index.ts file, if the error code is -4058, the requested path does not exist, and 404.html is returned.

If I request: http://localhost:8888/x.html obvious path does not exist, the page will display properly 404 and pictures.

But if the requested path contains an additional layer of directories, for example:http://localhost:8888/xxx/x.html

Found the picture can not display! We opened Network and found that the request path for 404.png was changed to images/404.png in directory XXX. Images /404.png is in the public directory.

This is because SRC writes relative paths: so when I add an extra layer of directory XXX, I request XXX /images/404.png

Just write the absolute path<img src="/images/404.png" alt="">And then put the catalogpublicbecome/Which is the current root directory: mouse over public, right click,Mark Directory as Resource Root

No matter how many nonexistent paths I then request in the directory, the 404. PNG request SRC will always be public images/404