Related knowledge points

  • Nodemon tools
  • 404 pages
  • Status code and request header and response header
  • File type MIME
  • Processing of dynamic resources

Nodemon tools

Tools like this allow us to use Node to execute code that is loaded into memory to speed things up. However, When the JS code on our hard drive changes, Node will not automatically detect and reload, so we need to restart the server again. And that’s very cumbersome, and that’s where these tools have to come in. When our code changes, it automatically restarts The Node for us.

Nodemon is recommended. Module of utility class, it is best not to install global. Since each project may use a different version of Nodemon, a project with a higher version may fail if it uses a lower version

The installation

npm i -D nodemon

yarn add -D nodemon

run

  • Locate the directory of the execution file and then Nodemon + executes the file

  • Use package.json and run NPM start in the terminal

    "scripts": {
      "start": "nodemon app.js"
    },
    Copy the code

404 pages

When we work with a resource, we need to prepare an error page for it. The user may not be accessing the correct address. If the access address is incorrect, we can prompt the user, and the status code should be 404. Prevent server errors.

  if(url.startsWith('/static')) {// Read the static resource file if the requested URL is /static
      let path = __dirname + url;

      try{
          content = fs.readFileSync(path);
          res.write(content);

      }catch (e){
          content = fs.readFileSync('./static/404.html');
          res.write(content);

      }finally{ res.end(); }}Copy the code

Status code and request header and response header

Response code points five types, by their first number: 1 xx: information, request received, continue to deal with 2 xx: success, actions have been successfully received, understand and adopt 3 xx: redirect, in order to complete the request, must further implement the action of 4 xx: client error, request contain grammatical errors or cannot be achieved 5 xx: Server error. The server was unable to fulfill an apparently invalid request

Request headers and response headers

The HTTP request header provides information about the request, response, or other sending entity. HTTP headers include general headers, request headers, response headers and entity headers. Each header field consists of a domain name, a colon (:), and the field value.

Request headers and response headers

  • Generic headers: Can be used for requests or responses and are associated with a transaction as a whole rather than as a specific resource.
  • Request headers: Allow clients to pass information about themselves and the form of a desired response.
  • Response headers: The server and the response that transmits information about itself.
  • Entity headers: Information that defines the resource to be transmitted. Can be used for requests or responses.

The content-type header is commonly used to tell the browser what Type of file to parse when it returns a file from the server.

Now, the problem is that if you set the response header to text/ HTML; charset=utf-8

It will cause the CSS file and so on not to display.

 if(url.startsWith('/static')) {// Read the static resource file if the requested URL is /static
      let path = __dirname + url;

      try{
          // Unified Settings
          res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
          content = fs.readFileSync(path);
          res.write(content);

      }catch (e){
          content = fs.readFileSync('./static/404.html');
          res.write(content);

      }finally{ res.end(); }}Copy the code

To solve this problem we propose the concept of file type

File type MIME

Multipurpose Internet Mail Extensions (MIME) Multipurpose Internet Mail Extensions. A type of file with a specified extension that the browser automatically opens when the file is accessed using the specified application. It is used to specify the name of a file customized by the client and the opening mode of some media files.

Common MIME types (generic) :

HTML Text/HTML

XML document.xml text/ XML

XHTML document.xhtml application/ XHTML + XML

TXT text/plain

RTF text.rtf application/ RTF

PDF document.pdf application/ PDF

Microsoft Word file. Word Application/Msword

PNG image. PNG image/ PNG

GIF graphics. GIF image/ GIF

JPEG Graphics.jpeg,.jpg image/ JPEG

Au Sound file. Au Audio /basic

MIDI music files mid,.midI audio/ MIDI,audio/ X-MIDI

RealAudio Music files.ra,.ram Audio/X-Pn-realAudio

MPEG files. MPG,. MPEG video/ MPEG

AVI file. AVI Video/X-MSVideo

GZIP file. Gz Application /x-gzip

TAR file. TAR application/x-tar

Any binary data application/ OCtet-stream

We can prepare a mine.json. This contains the corresponding header information for all file types

The data structure looks like this

"323":"text/h323" ,
Copy the code

We can make it look like this

      try {
            // Unified Settings
            // res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
            / / set the mime

            content = fs.readFileSync(path);
            let lastIndex = path.lastIndexOf('. ');
            let ext = path.substring(lastIndex);
            console.log('ext', ext);
            /* * ext .html ext .css ext .jpeg * */
            let mineName = mine[ext];
            console.log(ext,mineName)
            res.writeHead(200, {'Content-Type':mineName}); res.write(content); }...Copy the code

Processing of dynamic resources

Some data we need to fetch from the database, but for example an array of objects. How are we going to loop this data into our pages, and there’s probably going to be a loop, a judgment. How to display it correctly. This is where the template engine comes in. Nunjucks is used as an example

Nunjucks tutorial

However, with the advent of Vue React, this template reference is much less used. Check out the tutorial here.

Note that Nunjucks must be configured with the Environment first. Tell it in which context you want the code to run

Views is the folder where the template directory exists and then uses their templates

// the FileSystemLoader is available if in node
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('views'));

var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('views'),
                          { autoescape: false });

var env = new nunjucks.Environment([new nunjucks.FileSystemLoader('views'),
                           new MyCustomLoader()]);

// the WebLoader is available if in the browser
var env = new nunjucks.Environment(new nunjucks.WebLoader('/views'));
Copy the code

Then call the render function

render

render

nunjucks.render(name, [context], [callback])
Copy the code

Render mode requires two parameters, template name name and data context. If callback exists, it will be called when rendering is complete, with the first argument being an error and the second being the result returned. If it is not present, the render method returns the result directly, throwing an error on an error. See more about asynchrony support.

var res = nunjucks.render('foo.html');

var res = nunjucks.render('foo.html', { username: 'James' });

nunjucks.render('async.html'.function(err, res) {});Copy the code

Other loop functions such as {{}} syntax can be written in foo. HTML

More Template apis

github

The code address