Express Quick Use

Express Chinese network: expressjs.com.cn   
 Insert picture description here

1. What is Express?

Wikipedia summary: 
  Express.js or Express for short, is a web application framework for Node.js, released as free and open source software under the MIT license. It is designed to build web applications and APIs. It has been called the de facto standard for the server framework for Node.js.
  The original author, TJ Holowaychuk, described it as a server inspired by Sinatra, meaning it was relatively minimal, with many features obtained in the form of plug-ins. Express is the back-end component of the MEAN software stack, and the other components are the MongoDB database software and the AngularJS front-end framework.

The following is my personal understanding of Expres

  1. The relationship between Express and Node:
      -The Expres framework is the Node framework in the background, and its role is equivalent to the jQuery framework of JS.
      -The philosophy of Express is to act as a thin layer between your idea and the server.
  2. What are the problems with native Node development?
      -It is inconvenient to render static pages, you need to handle each HTTP request, and you need to consider the 304 problem
      -The routing processing code is not intuitive and clear, and you need to write a lot of regular expressions and string functions
      -Cannot concentrate on writing business, you have to consider many other things As a module
  3. Express overall perception
      -amazing routing capabilities, regular data extraction capabilities are sufficient for general work
      -static file processing capabilities, one-line solution
      -template engine cooperation, intuitive and clear

Second, quickly build a Node.js server under the Express framework

NPM 安装

	//通常的安装模式都是使用npm,Node.js的安装方式据说不介绍了(官网下载下一步即可)
	$ npm install express --save

	// 安装完成后基本目录结构
	.
	├── app.js
	├── node_modules
	│   ├── ...
	│	├── express
	│   └── ...
	├── package-lock.json
	└── package.json

$ node app.js 运行Node服务器

	const express = require('express');		// express 模块引入
	const app = express();
	const port = 3000;		// 设置端口号
	
	app.get('/', (req, res) => res.send('Hello Express'));
	
	app.listen(port);		// 监听端口3000

Browser visit http://127.0.0.1:3000
Insert picture description here

Three, Express routing

学习路由使用前,可以先了解下 URL 字符串与 URL 对象

URL strings are structured strings that contain multiple components with different meanings. The URL object returned after parsing the string, each attribute corresponds to each component of the string.
Insert picture description here

1) app.get (URL, callback) receives GET data

  • Use the specified callback function to route the HTTP GET request to the specified path.
  • The parameters of the GET request are in the URL. In the native Node, the GET request requires a urlmodule to identify the parameter string. In Express, you do not need to use urlmodules, you can use the req.queryobject directly
	const express = require('express');
	const app = express();
	app.get('/', (req, res, next) => {
		let GET = req.query;		// 查询字符串 search
	    console.log(GET);
	    res.send("Hello Express");
	});
	app.listen(3000);

Browser visit  http://127.0.0.1:3000/?username=“code”&userpwd=“123456 ”
Insert picture description here
terminal:
Insert picture description here

2)app.post(“URL”,callback)

  • Use the specified callback function to route the HTTP POST request to the specified path
  • POST requests cannot be obtained directly in Express, and body-parsermodules must be used . After use, the req.bodyparameters will be available . If the form contains file uploads, you also need to use the formidablemodule.
	const express = require('express');
	const app = express();
	let fs = require("fs");
	const bodyParser = require("body-parser");
	app.use(bodyParser.urlencoded({ extended: false }));
	app.get('/index', (req, res) => fs.readFile("./index.html", (err,data) => res.end(data)));	// 读取表单页面
	app.post('/insert', (req, res, next) => {
		 let POST = req.body
    	console.log(POST)
	    res.send("Hello Express");
	})
	app.listen(3000)

The browser accesses the  http://127.0.0.1:3000/index
  form to enter the data request for the <form action="/insert" method="POST">
Insert picture description here
Insert picture description here
terminal:
Insert picture description here

3)app.use()

  • It is also a middleware get. The postdifference is that its URL does not match exactly, and useit can be expanded infinitely.
  • When the path is not written, it is actually equivalent to "/", that is, all URLs
	let express = require("express");
	let app = express();
	
	// 指定一级路径
	app.use("/public", (req, res) => {
	    // 'http://127.0.0.1:3000/public/xxx/new.html?user=json&age=12#1d=3'
	    res.write(req.originalUrl + "\n");   // 原始路径 '/public/xxx/new.html?user=json&age=12'
	    res.write(req.baseUrl + "\n");       // 一级路径 '/public'
	    res.write(req.path + "\n");          // 追加路径 '/xxx/ccc/new.html'
	});
	
	app.listen(3000);

4)app.use("/url", express.static("./fileName"));

  • app.use (express.static ()) provides a static service
  • app.use(express.static("./fileName"))Is to add some traversal places for us with specific functions
  • Do not write detailed routing, you can directly access the static("./fileName")fileName fileindex.html
  • For route expansion, you can access the files under the expansion path (access if no detailed file is specified index.html), and return Cannot if the file does not exist ...
	let express = require("express");
	let app = express();
	app.use(express.static("./public"));
	// app.use("/pub", express.static("./public"));
	app.listen(3000);

5) Express content rendering

  • In most cases, the rendering content is res.render (), which will be rendered according to the template file in views. If you do n’t want to use the views folder and want to customize the folder, then app.set (“views”, “xxx”)
  • To quickly test the webpage, you can use res.send (), this function will automatically help us set the content-type header and 200 status code according to the content
  • Want to use different status codes: res.status (404) .send (“Sorry, We Cannot Find That!”);
  • Want to use different content-type: res.set ("content-type", "text / html");
Published 40 original articles · won 31 · views 2765

Guess you like

Origin blog.csdn.net/CodingmanNAN/article/details/105006957