node_express 프레임워크 01

01_기본 구조 표현

참고: app.get은 get 메서드를 지정합니다. app.all이면 모든 요청 메서드(예: 게시물 삭제 포함)를 지정하고 app.get('/')은 루트 경로에 액세스합니다. 다른 경로: 예를 들어 /home, 결과가 없습니다. 이것은 vueRouter와 매우 유사합니다. 경로는 응답을 지정해야 하며, 그렇지 않으면 404 페이지에 응답해야 합니다.

const express = require("express");

const app = express();

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

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

02_express 요청 매개변수 가져오기

주로 native http와 express의 전용 방식이며 express는 http 방식과 호환됩니다. 

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는 경로에 의해 전달되는 매개변수를 가져옵니다.

참고: 콜론 시작 부분의 매개변수는 req.params를 통해 가져옵니다. 매개변수 이름과 ?

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_익스프레스 응답 설정

주로 native http와 express의 전용 방식이며 express는 http 방식과 호환됩니다. 

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_글로벌 및 라우팅 미들웨어

두 개의 케이스가 연결된 글로벌 및 라우팅 미들웨어

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_정적 자원 미들웨어

예를 들어 경로 아래의 그림에 직접 액세스합니다. 그림을 직접 표시할 수 있습니다.

 정적 리소스와 라우팅 규칙이 동시에 일치하는 경우: 예를 들어 public 아래에 index.html이 있고 라우팅에도 app.get('/index.html')이 있는 경우 다음 순서와 관련이 있습니다. 코드는 먼저 일치하는 사람이 응답합니다. js 코드는 위에서 아래로, 왼쪽에서 오른쪽으로 실행됩니다.

일반적으로 라우팅은 뉴스, 일간지와 같은 동적 자원에 대응하지만 js, css 코드, 이미지, 동영상은 모두 정적 자원이므로 정적 자원 미들웨어를 사용하는 것이 더 적합합니다.

/**
 * 之前我们响应客户端都是先读文件再返回用户文件,这是很不方便,
 * 我们采用静态资源中间件后可以简化很多
 * 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 미들웨어는  요청 후 본문을 가져옵니다.

body-parser는 요청 본문을 가져오고 클릭 링크를 설치하고 사용하는 플러그인입니다.

사례: 사용자 로그인 사용자 이름(사용자 이름)과 비밀번호(password)를 얻습니다. 우선 이것은 게시물입니다.사용자가 로그인 버튼을 클릭하면 브라우저가 게시물 요청을 시작하고 사용자 이름과 암호를 얻어야 합니다.

요청에 포함된 매개변수는 다음과 같습니다.

반환 데이터:

 아래와 같이 코드 쇼: 

/**
 * 获取请求体的中间件,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_안티리치 미들웨어

다른 서버가 우리 서버의 리소스를 훔치는 것을 방지하기 위해 요청 헤더의 호스트 이름이 실제로 글로벌 미들웨어인 우리 서버 주소 ip인지 감지해야 합니다.

아래와 같이 코드 쇼:

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 프레임워크 02_You Xiaobei의 블로그 - CSDN 블로그

추천

출처blog.csdn.net/m0_66492535/article/details/129879758