Express learning environment configuration and the first express project

express learning (1)
Environment configuration and the first express project

CSDN home page: jcLee95

Email: 291148484@163.com

[task]:

  • Install express;
  • Create the first express project;
  • Master the express project structure;
  • Understand the principle of expres routing;
  • Understand the express view and the relationship between routing and view;

1. Install Express

1.1 installation mode through npm

npm install -g express-generator

1.2 installation method through yarn

yarn global add express-generator

2. Create a project named myproject

express myproject

Run the command as shown in the figure. You can see that after execution, a new project named "myproject" is added to the directory, that is, our newly created project folder:

The initial structure of the project directory is shown in the following figure:

3. Initial application master file app.js

The contents and meanings are noted as follows:

var createError = require('http-errors');          // http error handling module
var express = require('express');                  // express module
var path = require('path');                        // path module
var cookieParser = require('cookie-parser');       // cookie processing module
var logger = require('morgan');                    // Log management module

var indexRouter = require('./routes/index');       // 'index.js' file in routing directory	
var usersRouter = require('./routes/users');       // 'user.js' file in routing directory

var app = express();                               // Create an express application instance

// view engine setup
app.set('views', path.join(__dirname, 'views'));               // Define page directory
app.set('view engine', 'jade');                                // Define page template engine

app.use(logger('dev'));                                        // Define log print level
app.use(express.json());                                       // Define JSON format to process data
app.use(express.urlencoded({ extended: false }));              // Defines how to use urlencode to process datasets. The querystring module parses data
app.use(cookieParser());                                       // Defines the object to be processed using cookie s
app.use(express.static(path.join(__dirname, 'public')));       // Define static resource directory

app.use('/', indexRouter);                    // The definition points to index.js
app.use('/users', usersRouter);               // Definition points to users.js

app.use(function(req, res, next) {            // Definition 404 error handling
  next(createError(404));
});

app.use(function(err, req, res, next) {       // Define other error handling
  // Setting locals only takes effect in the development environment
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);            // Return http status code
  res.render('error');                      // Render error page
});

module.exports = app;

4. Get familiar with express Router and view

4.1 routing documents

express automatically initializes two default project routing files in the routing subdirectory routes: index.js and users.js:

index.js file

var express = require('express');                // Introducing express
var router = express.Router();                   // Introducing express router objects

router.get('/', function(req, res, next) {       // Define a route whose request method is GET, and its route value is' / ', that is, the home page.
  res.render('index', { title: 'Express' });     // Route to the view template file named 'index' for rendering, and break into the view. The value of the title parameter is' Express'`
});

module.exports = router;                         // Export route

users.js file

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

We can also name the routing file other names with certain meanings, but no matter what name we name the routing file, there are generally the following steps to define a route:

  • Introduce express;
  • Introduce express router object;
  • Determine what the route is. For example, the root route '/' represents the home page;
  • Determine the request method corresponding to the route, such as GET, POST, DELETE, etc;
  • ★ determine the return object of the response. For example, the render() method corresponds to a rendered page, the final response is an HTML page string rendered by combining the template in the view file, and the send() method directly sends a content as an HTTP response. Refer to the following table:
    • Return object Response:
      methoddescribeexplain
      Response.render()Render Page He has three parameters,
      ·view (required) is a string representing the file name (relative path) used for rendering;
      ·Local (optional) is an object that defines the local variable of the page for the attribute;
      ·Callback (optional), a function, is a callback function. Returns possible errors and rendered strings, but does not perform an automatic response. This method is called inside next(err) when an error occurs.
      Response.send()Send HTTP responseThis method sends an HTTP response to the requester and can receive a parameter, which can be of any type. For example, a Buffer object, a string, an object, or an array. For example, res.send (new Buffer ('Hello ');, Another example is res.send('some string '), another example is res.send({key:'value '})
      Response.json()Returns string data in JSON formatFor example, res.json({name:'JACK'}), we passed in a js object, but through the json() method, it will be automatically converted into a JSON format string and sent to the requester through HTTP.
      Response.status()Set HTTP status codeFor example, res.status(403).end(), the returned status code can be seen in Postman.
      Response.redirect()Jump to the specified routeFor example, res.redirect('/home').

4.2 view files

The default template engine file of the express view ends with the suffix. Jade (which can be set in app.js above), which is equivalent to an HTML template file. In the initial project, three view files, index.jade, error.jade and layout.jade, are created for us by default:

layout.jade file

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

index.jade file

extends layout

block content
  h1= title
  p Welcome to #{title}

error.jade file

extends layout

block content
  h1= message
  h2= error.status
  pre #{error.stack}

It can be seen that the above layout.jade is the common part of index.jade and error.jade. The former is separated into a file, so that the latter two inherit the content from the former through the extensions template keyword.

4.3 the installation project depends on and runs the project

(1) Install project dependencies

You may notice that there is no folder named "node_modules" in the project we created, which means that the dependencies are not automatically installed for us when creating the express project, and we need to install them manually. Execute the following command:

yarn install

Or you use npm:

npm install

(2) Run project (start Web Service)

After installing the project dependency, you can start the Web service, that is, run the file / bin/www. Open package.json and find the following contents:

{
  "name": "myproject",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1"
  }

Note that we can directly run / bin/www through start at the root directory of the project:

yarn start

(or you use npm):

npm start

Now, let's open the client (browser) to see the effect! express uses the local 3000 port by default. Enter it in the browser http://127.0.0.1:3000 perhaps http://localhost:3000 , you can see the following page:

success!

Tags: node.js express

Posted on Mon, 27 Sep 2021 14:30:04 -0400 by devarticles