node_express framework 01

01_express basic structure

Note: app.get specifies the get method. If it is app.all, it specifies all the request methods (for example: post delete is included), and app.get('/') accesses the root path. If you access other paths: for example /home, there is no result. This is very similar to vueRouter. The path should specify the response, otherwise it should respond to a 404 page.

const express = require("express");

const app = express();

app.get("/", (req, res) => {
  res.send("hello");
});

app.listen(8080, () => {
  console.log("服务开启在 8080 端口");
});

02_express get request parameters

It is mainly the exclusive method of native http and express, and express is compatible with http method 

const express = require("express");
const app = express();

/**
 * 获取请求参数的方法有两种,1、原生http 的 ,2、express 专属的
 */
app.get("/home", (req, res) => {
  // 1.原生 http
  console.log(req.url); // 获取请求的路径 /home?query ....
  console.log(req.method); // 获取请求的方法,GET ,实际上这里已经指定了是 get (app.get )
  console.log(req.httpVersion); // 获取 http 版本
  console.log(req.headers); // 获取请求头 1.1

  //2. express
  console.log(req.query); // 获取查询字符串 ?query='查询字符串' { query: "'查询字符串'" }
  console.log(req.get("host")); // 获取某个指定的请求头 localhost:8080

  res.send("响应体");
});

app.listen(8080, () => {
  console.log("服务开启");
});

03_express gets the parameters carried by the route

Note: the parameter at the beginning of the colon is obtained through req.params. The parameter name, and the ? .

const express = require("express");

const app = express();

// 获取请求时携带的id参数, http://localhost:8080/home:12345
// 注意请求时是一定要有参数不然不会响应
app.get("/home:id", (req, res) => {
  res.send("你的请求参数为" + req.params.id); // 12345
});

// 默认 1314
app.get("/home", (req, res) => {
  // 没有参数重定向
  res.redirect("http://localhost:8080/home:1314");
});

app.listen(8080, () => {
  console.log("服务开启在 8080 端口");
});

04_express response settings

It is mainly the exclusive method of native http and express, and express is compatible with http method 

const express = require("express");
const app = express();

app.get("/home", (req, res) => {
  // 1. http 兼容
  res.statusCode = 200;
  res.statusMessage = "xxx"; // 在响应码之后
  res.setHeader("header", "id header");
  res.write("响应体");
  res.end("xxx");

  // 2. express 的响应
  res.status(500); // 状态码
  res.set("xxx", "yyy"); // 设置一个 xxx 响应头
  res.send("express 的 send 方法不会乱码"); // 响应体
  res.status(300).set("xxx", "yyy").send("连贯的操作");

  // 3. 其他的功能
  res.redirect("http://youxiaobei.top"); // 重定向
  res.download("./文件名"); // 下载响应,启动下载
  res.json(); // 响应 JSON
  res.sendFile(__dirname + "/某个文件路径"); // 响应文件内容
});

app.listen(8080, () => {
  console.log("服务开启");
});

05_Global and routing middleware

Global and routing middleware, with two cases attached

const express = require("express");
const app = express();
const fs = require("fs");

/**
 * 中间件本身就是就是一个函数,接收三个参数,req,res ,next
 * 他的作用就是简化操作和代码
 * 一般分为两个类型,全局和路由中间件
 * 1. 全局
 * 每一个请求到服务端之后都会执行全局中间件函数
 * 2. 路由中间件
 * 在每一个请求值得路由的请求发生后执行的中间件函数
 */

// 定义全局中间件,实现功能每次有访问就记录 ip 和 请求路径 (全局中间件的案例)
const GlobalMV = (req, res, next) => {
  // 获取 ip 和路径
  let { hostname, url } = req;
  // 存储数据
  fs.appendFileSync("./access.log", `${hostname}  ${url} \r\n`);
  next(); // 执行之后的函数
};

// 定义路由中间件,实现权限认证(路由中间件的案例)
const roterMV = (req, res, next) => {
  // 根据查询参数password确定密码权限  http://localhost:8080/home?password=001223
  if (req.query.password === "001223") {
    console.log("密码正确");
    next(); // 执行之后的函数
  } else {
    res.send("密码错误");
  }
};

// 全局中间件,需要 use 注册
app.use(GlobalMV);

// 局部中间件
app.get("/home", roterMV, (req, res) => {
  res.send("响应体");
});

app.listen(8080, () => {
  console.log("服务开启");
});

 06_Static resource middleware

We directly access the pictures under the path, for example: the pictures can be displayed directly

 If static resources and routing rules match at the same time: for example: there is an index.html under public, and the routing also has an app.get('/index.html'), then it is related to the order of the code, whoever matches first will respond, js The code runs from top to bottom, left to right.

Generally, routing responds to dynamic resources, such as news and daily reports, but js css codes, pictures and videos are all static resources, and it is more appropriate to use static resource middleware.

/**
 * 之前我们响应客户端都是先读文件再返回用户文件,这是很不方便,
 * 我们采用静态资源中间件后可以简化很多
 * express.static('路径')
 */

const express = require("express");
const app = express();

// 注册static目录为静态资源中间件
const staticMV = express.static("./static");
app.use(staticMV);

// 启动服务,可直接访问静态资源
app.listen(8080, () => {
  console.log("服务启动");
});

07_bodyParser middleware gets  post request body

body-parser is a plugin to get the request body, install and use click link.

Case: Obtain the user login username (user name) and password (password). First of all, this is a post. When the user clicks the login button, the browser will initiate a post request, and we need to obtain the user name and password.

The parameters carried in the request are as follows

return data:

 code show as below: 

/**
 * 获取请求体的中间件,bodyParser, 把请求的参数解析好,添加到 req.body 对象上
 * npm i body-parser 下载插件
 */
const express = require("express");
const bodyParser = require("body-parser");
const app = express();

// 解析 string 格式的
app.use(bodyParser.urlencoded({ extended: false })); // 全局使用

// 解析 json 格式的
app.use(bodyParser.json());

// 返回一个表格提交,实现post
app.get("/login", (req, res) => {
  res.send(
    "<h2>登陆</h2><form method='post' action='/login'><input text='用户名' name='username'></input><input text='密码' name='password'></input><button>登陆</button></form>"
  );
});

app.post("/login", (req, res) => {
  // 获取请求体,body-parser 插件会添加一个 req.body 对象
  res.send(req.body);
});

app.listen(8080, () => {
  console.log("服务开启");
});

08_Anti-leech middleware

In order to prevent other servers from stealing the resources of our own server, we need to detect whether the host name in the request header is our server address ip, which is actually a global middleware

code show as below:

const express = require("express");
const app = express();
/**
 * 为了防止别的服务器盗用自己服务器的资源
 * 检测 请求头中的 hostname 是否为我们的服务器地址ip
 * 这其实是一个全局中间件
 */

const TextMV = (req, res, next) => {
  // 获取 hostname
  const hostname = req.hostname;
  // 判断是否为自己的主机地址
  if (hostname !== "127.0.0.1") {
    res.status(404);
    res.send("404 NOT FOUND");
    return;
  }
  next();
};

app.get("*", TextMV, (req, res) => {
  res.send("获取了资源哦");
});

app.listen(8080, () => {
  console.log("服务开启在 8080 端口");
});

node_express framework 02_You Xiaobei's Blog - CSDN Blog

Guess you like

Origin blog.csdn.net/m0_66492535/article/details/129879758
Recommended