[Express learning notes-1] quick start

I. Basic Concepts

Express is a simple and flexible node.js Web application framework, which provides a series of powerful features to help you create various Web applications and rich HTTP tools. Express can be used to quickly build a full-featured website with a set of robust features, which can be used to develop single page, multi page and hybrid Web applications.

2. Quick start

1. First, assume that you have installed node.js (if not, please install node.js first), and then create a working directory.

$ mkdir express-start
$ cd express-start

2. Create a package.json file for your application through npm init command (if you don't know package.json, please Baidu yourself).

 $ npm init

Note: this command will ask you to enter several parameters, such as the name and version of the application You can directly press enter to accept most of the default settings, except for the following: enter app.js or the name you want, which is the entry file of the current application. If you want to use the default index.js file name, just press enter.

entry point: (index.js)

3. Install Express in the Express start directory and save it to the dependency list.

npm install express --save

4. Create app.js in the following directory of the project (note in the second step: what is the name of the entry file? What is the name of this file). The following is the content of app.js file:

const express = require('express')
const app = express()

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Example app listening on port 3000!'))

5. Start the project and visit http://localhost:3000/

node app.js

III. Express application generator

An application skeleton can be created quickly through the application generator tool express generator, which includes the express command line tool.

1. Install express generator:

npm install express-generator -g

-The h parameter lists all available command line parameters:

$ express -h

  Usage: express [options] [dir]


    -h, --help          Output usage
        --version       Output version number
    -e, --ejs           Add pair ejs Template engine support
        --hbs           Add pair handlebars Template engine support
        --pug           Add pair pug Template engine support
    -H, --hogan         Add pair hogan.js Template engine support
        --no-view       Create a project without a view engine
    -v, --view <engine> Add pair view engine( view) <engine> Support (ejs|hbs|hjs|jade|pug|twig|vash) (The default is jade Template engine)
    -c, --css <engine>  Add style sheet engine <engine> Support (less|stylus|compass|sass) (The default is normal css Document)
        --git           Add to .gitignore
    -f, --force         Force creation in a non empty directory

2. Create a new project and run the following command:

express project-name   // Simple project creation
express --css=less --view=pug project-name  // Create project with parameters

The operation results are as follows:
3. Proceed as directed

cd express-start // Go in to the project path
npm install // Install dependency package
npm start //Startup project

Visit http://localhost : 3000 /, you will see the following interface.

IV. explanation of project structure

Let's go back to the generated project directory and open our express start folder, as shown in the figure

bin: store executable
node_modules: store the modules installed in package.json. When you add the dependent modules in package.json and install them, store them in this folder.
public: store image, css, js and other files
routes: store route files
views: store view files or template files
app.js: startup file, or entry file
Package.json: stores project information and module dependencies. When adding dependent modules in dependencies, run npm install. npm will check package.json in the current directory and install all specified modules automatically

Open app.js and let's see what's in it:

var createError = require('http-errors');
var express = require('express');  //Load the express module
var path = require('path'); //Path module
var cookieParser = require('cookie-parser'); //This is a tool for parsing cookies. Through req.cookies, you can get the cookies passed in and turn them into objects.
var logger = require('morgan'); //In the console, display the information of req request

// Routing information (interface address), stored in the root directory of routes
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/person');
var app = express();

// view engine setup template start
app.set('views', path.join(__dirname, 'views'));  //Set view root
app.set('view engine', 'jade'); //Format view

// Load Middleware
app.use(logger('dev')); // Log Middleware
app.use(express.json()); // Parse the middleware of json.
app.use(express.urlencoded({ extended: false })); // Middleware for parsing urlencoded request body
app.use(cookieParser()); // Middleware for parsing cookie s

// Set the public folder to the directory where static files are stored
app.use(express.static(path.join(__dirname, 'public')));

//Configure route, ('custom path', interface address set above)
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);

module.exports = app;

V. Using html template for Express

1. install ejs

npm install ejs --save

2. introduce ejs

var ejs = require('ejs');

3. use

app.set('views', path.join(__dirname, 'views'));
app.engine('html', ejs.__express);
app.set('view engine', 'html');

app.set('views', path.join(__dirname, 'views'));  //Set view root
app.set('view engine', 'jade'); //Format view

4. Change the original. jade file to. html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
     <link rel="stylesheet" type="text/css" href="css/home.css">
     <h1>Welcome to <%= title%></h1>

Tags: node.js npm JSON less Handlebars

Posted on Tue, 12 Nov 2019 02:45:00 -0500 by ntsf