NodeJs web project framework Express notes

installation

The following are all carried out using Yarn. Environmental premise: NodeJS (and its own npm) has been installed, Yarn has been installed

# Global installation
yarn global add express-generator@4

#View version
>express --version
4.16.1

 

Create project

# Create project expressite, -f is used to check whether the directory is empty, -v is used to specify the template engine, you can choose Pug, Mustache, EJS
express -f -v pug expressite

# Use EJS template engine
express -v ejs expressite

# Initialize node_modules
cd expressite
yarn install

 

run

As you can see in the package.json, there is only one "start" in the scripts: "node ./bin/www", so start it with the following command

# 'start' is an item in scripts
yarn start

 Visit http://127.0.0.1:3000 to see the page

Directory Structure

bin

The www file is the execution entry, which can modify the default port

public

Place static resource files

routes

Here is the place to write the request and response, which is equivalent to the Controller in Java Spring, and construct the request response method:

router.get('/get_session', function(req, res, next) {
  console.info(req.query);
  var sid = req.query.sid;
  if (sid == undefined || sid.length == 0) {
    res.send('Invalid sid');
  } else {
    res.send(JSON.stringify({sid:sid, start:123123123, update:123123125, userId:"132341234"}));
  }
});

Use req.params to get the input data of the post, use req.query to get the input data of get, and use res.send to return the string response.

views

Template file directory

 

Guess you like

Origin www.cnblogs.com/milton/p/12737462.html