目录

Nodejs Express4 入门实战笔记02 请求req与响应res及Cookie

本系列的目标快速上手 Express 框架, 基于官方文档归纳

参考中文文档:https://nodejs.cn/express/4x/api/

项目: https://github.com/eezd/cli-template/tree/main/nodejs-express-template

环境: Express 4.16

这个简单的例子我就不解释了

app.js

app.use("/", indexRouter);

routes/index.js

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

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
  • params
  • query
// http://127.0.0.1:8888/user/tom?age=18
router.get("/user/:id", function (req, res, next) {
  console.log(req.params.id); // tom

  console.log(req.query); // { age: '18' }
  res.render("index", { title: "Express123" });
});
  • body
    • 需要注意,这里只能传递 JSON格式的数据,因为你在上面设置了 express.json()
router.post("/data", function (req, res, next) {
  console.log(req.body); // { userId: 'u-123' }
  res.render("index", { title: "Express123" });
});

// 测试请求
const body = { userId: "u-123" };
const res = await axios.put("http://localhost:8888", body);
  • baseUrl: 挂载实例的 url
var app = express.Router();

app.get("/jp", function (req, res) {
  console.log(req.baseUrl); // /users
  res.send("Konichiwa!");
});

app.use("/users", app);
  • originalUrl: 保留了原始请求 URL
app.use("/admin", function (req, res, next) {
  // GET 'http://127.0.0.1:8888/admin/new?sort=desc'
  console.dir(req.originalUrl); // '/admin/new?sort=desc'
  console.dir(req.baseUrl); // '/admin'
  console.dir(req.path); // '/new'
  console.dir(req.url); // '/new?sort=desc'
  next();
});

当响应在客户端的缓存中仍然是 “fresh” 时,返回 true,否则返回 false,表示客户端缓存现在已经过时,应该发送完整的响应。

当客户端发送 Cache-Control: no-cache 请求头指示端到端的重新加载请求时,该模块将返回 false 以使处理这些请求透明。

console.dir(req.fresh);
// => true
  • hostname: 包含从 Host HTTP 标头派生的主机名。
    • 当 trust proxy 设置 不计算为 false 时,此属性将改为从 X-Forwarded-Host 标头字段中获取值。此标头可以由客户端或代理设置。
    • 如果请求中有多个 X-Forwarded-Host 标头,则使用第一个标头的值。这包括一个带有逗号分隔值的标头,其中使用了第一个值。
// Host: "example.com:3000"
console.dir(req.hostname);
// => 'example.com'
  • ip: 包含请求的远程 IP 地址。
console.dir(req.ip);
// => '127.0.0.1'

包含请求协议字符串:http 或(对于 TLS 请求)https

console.dir(req.protocol);
// => 'http'

如果建立了 TLS 连接,则为 true 的布尔属性。相当于:

console.dir(req.protocol === "https");
// => true

响应, 是指返回数据给客户端

  • json: 响应 JSON 数据
res.json(null);
res.json({ user: "tobi" });
res.status(500).json({ error: "message" });
  • 发送普通响应信息。
res.send(Buffer.from("whoop"));
res.send({ some: "json" });
res.send("<p>some html</p>");
res.status(404).send("Sorry, we cannot find that!");
res.status(500).send({ error: "something blew up" });
  • 发送状态码
res.sendStatus(404)
res.redirect("/foo/bar");
res.redirect("http://example.com");
res.redirect(301, "http://example.com");
res.redirect("../login");
  • 发送页面,对应你的 views 文件夹下面的模板页面。
// send the rendered view to the client
res.render("index");

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render("index", function (err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render("user", { name: "Tobi" }, function (err, html) {
  // ...
});
res.get("Content-Type");
// => "text/plain"

针对请求对象的 Accept HTTP 标头响应内容。

res.format({
  "text/plain": function () {
    res.send("hey");
  },

  "text/html": function () {
    res.send("<p>hey</p>");
  },

  "application/json": function () {
    res.send({ message: "hey" });
  },

  default: function () {
    // log the request and respond with 406
    res.status(406).send("Not Acceptable");
  },
});
res.format({
  text: function () {
    res.send('hey')
  },

  html: function () {
    res.send('<p>hey</p>')
  },

  json: function () {
    res.send({ message: 'hey' })
  }

  default: function () {
    // log the request and respond with 406
    res.status(406).send('Not Acceptable')
  }
})
res.end();
res.status(404).end();

用于检查响应头是否已经发送。

app.get("/", function (req, res) {
  console.dir(res.headersSent); // false
  res.send("OK");
  console.dir(res.headersSent); // true
});

需要 cookie-parser 中间件

var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
  • httpOnly: 设置无法通过 JavaScript 访问
  • path: '/': 指定 Cookie 的路径为根路径 ‘/’,表示整个网站都可以访问这个 Cookie
  • maxAge: 过期时间
  • httpOnly: cookie 只能由 Web 服务器访问。
  • signed: 使用加密
app.use(cookieParser("abc123"));

app.get("/", function (req, res, next) {
  if (!req.cookies.username) {
    res.cookie("username", "Tom", {
      httpOnly: true,
      path: "/",
      maxAge: 86400000,
      httpOnly: true,
      signed: true,
    });
  } else {
    console.log("username: ", req.cookies.username);
  }

  res.send("hello world!");
});

你以及学会了大部分基本命令了,接下来我们结合下案例学习