广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Express框架reqres对象使用详解
  • 236
分享到

Express框架reqres对象使用详解

Express框架reqres对象Expressreqres 2023-03-24 17:03:41 236人浏览 安东尼
摘要

目录IncomingMessageServerResponse请求对象 req响应对象设置状态码如何来快速测试这些属性和方法呢?下面给出一些示例代码目录结构安装依赖小结Express

Express 请求 req 和响应 res 对象定义:

var req = Object.create(Http.IncomingMessage.prototype)
var res = Object.create(http.ServerResponse.prototype)
复制代码

下面是属性继承关系:

原型继承来源类
http.IncomingMessage.prototypeStream.Reabable
http.ServerResponse.prototypeIncomingMessage

IncomingMessage

 class IncomingMessage extends stream.Readable {
    constructor(Socket: Socket);
    aborted: boolean;
    httpVersion: string;
    httpVersionMajor: number;
    httpVersionMinor: number;
    complete: boolean;
    connection: Socket;
    socket: Socket;
    headers: IncomingHttpHeaders;
    rawHeaders: string[];
    trailers: nodejs.Dict<string>;
    rawTrailers: string[];
    setTimeout(msecs: number, callback?: () => void): this;
    method?: string | undefined;
    url?: string | undefined;
    statusCode?: number | undefined;
    statusMessage?: string | undefined;
    destroy(error?: Error): this;
}
复制代码

ServerResponse

class ServerResponse<Request extends IncomingMessage = IncomingMessage> extends OutGoingMessage<Request> {
    statusCode: number;
    statusMessage: string;
    constructor(req: Request);
    assignSocket(socket: Socket): void;
    detachSocket(socket: Socket): void;
    writeContinue(callback?: () => void): void;
    writeEarlyHints(hints: Record<string, string | string[]>, callback?: () => void): void;
    writeHead(
        statusCode: number,
        statusMessage?: string,
        headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],
    ): this;
    writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
    writeProcessing(): void;
}
复制代码

接下来的任务还是很简单,看看 express 是如何处理请求 req 对象上的属性和方法。

请求对象 req

在 req 对象上扩展方法

属性和方法名说明
get()/header()返回指定的 HTTP 请求头字段(不区分大小写的匹配)。
accepts()根据请求的 HTTP 标字段检查指定的内容类型是否可接受。
acceptsEncodings()返回指定编码的第一个接受编码。
acceptsCharsets()返回指定字符集的第一个接受的字符集。
acceptsLanguages()返回指定语言的第一个接受语言。
range()Range 标头解析器。
param()返回 req 对象中 params
is()如果传入请求的 内容类型 HTTP 头字段,则返回匹配的内容类型 匹配参数指定的 MIME 类型。

使用 defineGetter 函数扩展属性:

function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: true,
    enumerable: true,
    get: getter
  });
}
复制代码
属性说明
protocol协议
secure是否安全
ip请求的 ip 地址
ips请求头中的 ip 地址数组
subdomains请求中的子域名
path包含请求 URL 的路径部分。
hostname主机名
fresh是否为最新的
stale是否为过时的
xhr请求中是否包 xmlHTTPRequest 字符串

这是属性还是跟 HTTP 通信,前后端通信 xhr,如:完整的路径 path/protocol/secure/subdomains, ip 相关,服务器相关 fresh/stable。

响应对象

在 res 对象上扩展方法:

属性和方法名说明
status()设置响应状态码。
links()用给定的 links 设置头字段
send()发送 HTTP 响应。
JSON()发送 jsON 响应。
jsonp()发送 JSONP 响应。
sendStatus()发送状态码
sendFile()在给定的路径处传输文件。
sendfile()在给定的 .设置响应 HTTP 头字段 基于文件名的扩展名。
download()下载文件
type()将 HTTP 标头设置为由指定的。
fORMat()格式化请求对象的上内容
attachment()在响应头中添加额外的内容
append()将数据最加到尾部
set()/header()设置 http 头信息
get()获取指定 http 头数据
clearCookie()清除 cookie 内容
cookie()设置 cookie
location()将响应 HTTP 标头设置为指定的参数。
redirect()重定向地址
vary()使用 vary 方法添加字段到请求头
render()渲染模板中 html

设置状态码

res.status(203)
console.log(res.statusCode)
res.send("get v1: hello world!")
复制代码

如何来快速测试这些属性和方法呢?

  • 准备好接口, 熟悉 restful api 或者其他范式的形式接口
  • 准备写接口时的工具。curl(熟悉命令行)、工具(类似于:postman 等等)
  • 将工具接口与 express 的接口对应起来进行调试测试,验证属性。本项目使用

下面给出一些示例代码

目录结构

.
├── __tests__
├── babel.config.js
├── index.js
├── index.md
├── jest.config.js
├── node_modules
├── package.json
├── pnpm-lock.yaml
├── public
└── views
复制代码

安装依赖

  • views 中的 home.ejs 需要 ejs, 内容如下:
<html>
<head>
    <title>Home 页面</title>
</head>
<body>
    <h2>欢迎来到 Home 页面</h2>
</body>
</html>
复制代码

安装其他的依赖包:

pnpm install ejs babel-jest dirname-filename-esm jest nodemon supertest @babel/preset-React @babel/preset-env @babel/plugin-syntax-jsx @babel/core
复制代码

看看 package.json 项目配置

{
  "name": "debugger-source-code",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "nodemon index.js",
    "test": "NODE_OPTIONS=--experimental-vm-modules jest"
  },
  "keyWords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.21.0",
    "@babel/plugin-syntax-jsx": "^7.18.6",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-jest": "^29.4.3",
    "dirname-filename-esm": "^1.1.1",
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "jest": "^29.4.3",
    "nodemon": "^2.0.20",
    "supertest": "^6.3.3"
  }
}
复制代码

看看 babel 配置

export default {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-react",
  ],
};
复制代码

看看 eslint 配置

module.exports = {
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "overrides": [
    ],
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "rules": {
    }
}
复制代码

看看 jest 配置

export default {
  transform: {
    '\\.[jt]s?$': 'babel-jest'
  },
};
复制代码

express 主要服务 index.js

import express from "express";
import path from "path";
import { dirname } from "dirname-filename-esm";

const __dirname = dirname(import.meta);

const app = express();

app.set("view engine", "ejs");

app.use(express.static(path.join(__dirname, "public")));

app.get("/req", (req, res, next) => {
  console.log(req.protocol); // http 协议
  console.log(req.secure); //fals
  console.log(req.ip); //::1
  console.log(req.ips); // []
  console.log(req.subdomains); // []
  console.log(req.path); // /favicon.ico
  console.log(req.host); // localhost 已经被废弃
  console.log(req.hostname); // localhost
  console.log(req.fresh); // false
  console.log(req.stale); // true
  console.log(req.xhr); //false

  //------------- get ------------- //
  let a1 = req.get("set-cookie");
  console.log("set-cookie", a1); // undefined

  //------------- header ------------- //
  let a2 = req.header("set-cookie");
  console.log("set-cookie", a2); // undefined

  //------------- accepts ------------- //
  let b1 = req.accepts();
  console.log("accepts", b1);
  //   accepts [
  //   'image/avif',
  //   'image/WEBp',
  //   'image/apng',
  //   'image/svg+xml',
  //   'image*'
  // ]

  //------------- acceptsEncodings ------------- //
  let b2 = req.acceptsEncodings();
  console.log("acceptsEncodings", b2); //  [ 'gzip', 'deflate', 'br', 'identity' ]

  //------------- acceptsLanguages ------------- //
  let c1 = req.acceptsLanguages();
  console.log("acceptsLanguages", c1); // [ 'zh-CN', 'zh' ]

  //------------- range ------------- //
  let range = req.range(10, {});
  console.log("range", range); // undefined

  //------------- param ------------- //
  let param = req.param();
  console.log("param", param); // undefined

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

app.get("/res/status", (req, res, next) => {
  res.status(203);
  console.log(res.statusCode);
  res.send("get v1: hello world! and status code: 203 === " + res.statusCode);
});

app.get("/res/statusCode", (req, res, next) => {
  res.send("get v1: hello world! and status code:" + res.statusCode);
});

app.get("/res/links", (req, res, next) => {
  res.links({
    a: "http://localhost:3232",
  });
  res.send("links set"); // header Link filed
});

app.get("/res/send", (req, res, next) => {
  res.send("links set"); //type: string
});

app.get("/res/send/object", (req, res, next) => {
  res.send({ msg: "123" }); // type object json
});

app.get("/res/send/json", (req, res, next) => {
  res.json(JSON.stringify({ msg: "json" })); // type object json
});

app.get("/res/send/jsonp", (req, res, next) => {
  let fn = req.query.fn;
  let data = JSON.stringify({
    data: "mydata",
  });
  res.end(fn + data); // type object json
});

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

app.get("/res/send/sendFile", (req, res, next) => {
  res.sendFile(path.join(__dirname, "jest.config.js"));
});

app.get("/res/send/download", (req, res, next) => {
  res.download(path.join(__dirname, "jest.config.js"));
});

app.get("/res/send/type", (req, res, next) => {
  res.type(".html").send("<div>123</div>");

  // image/png
  console.log(res.get("Content-type"));
});

app.get("/res/send/format", (req, res, next) => {
  res.format({
    "text/html": function () {
      res.send("<div>This is html</div>");
    },
    "text/pain": function () {
      res.send("this is html text");
    },
    "application/json": function () {
      res.send({ message: "This is html json" });
    },
    default: function () {
      res.status(406).send("Not Acceptable");
    },
  });
});

app.get("/res/send/attachment", (req, res, next) => {
  res.attachment("index.md");
  console.log(req.get("Content-Disposition"));
  res.send("attachment");
  // 	attachment; filename="index.md"
});

app.get("/res/send/append", (req, res, next) => {
  res.append("Warning", "201 Warning");
  console.log(res.get("Warning")); // Warning	201 Warning
  res.send("append");
});

app.get("/res/send/set", (req, res, next) => {
  res.set("set8", "set8888"); //响应 header 中
  res.send("set");
});

app.get("/res/send/header", (req, res, next) => {
  res.header("set9", "set9999"); //响应 header 中
  res.send("set9");
});

app.get("/res/send/get", (req, res, next) => {
  res.set({
    "Content-Type": "text/plain",
    "Content-Length": "123",
    ETag: "12345",
  });
  let ct = res.get("Content-Type"); //响应 header 中
  res.send("[get => ]" + ct);
});

app.get("/res/send/cookie", (req, res, next) => {
  res.cookie("abc", "dd"); //响应 header 中
  res.send("cookie: abcdd");
});

app.get("/res/send/clearCookie", (req, res, next) => {
  res.cookie("abc", "dd");
  res.cookie("def", "xj");
  res.clearCookie("abc");
  res.send("cookie: abcdd");
});

app.get("/res/send/location", (req, res, next) => {
  res.location("http://demo.com");
  console.log(res.get("location")); // http://demo.com

  res.send(res.get("location"));
});

app.get("/res/send/redirect", (req, res, next) => {
  res.redirect("/res/send/redirect-new");
});

app.get("/res/send/redirect-new", (req, res, next) => {
  res.send("this is redirect-new");
});

app.get("/res/send/vary", (req, res, next) => {
  res.vary("User-Agent").send("Field added to the Vary response header");
});

app.get("/res/send/render", (req, res, next) => {
  res.render('home')
});

app.listen(3232, () => {
  console.log("listening on http://localhost:3232");
});
复制代码

小结

本文主要介绍了 express 的请求和响应对象,以及集成对象,各种用途,并使用一个实例,来进行说明。在测试实际接口时候,使用了 nodemon 来自动重启服务,使用 apifox 来保存接口重复发送测试接口。

以上就是Express框架req res对象使用详解的详细内容,更多关于Express框架req res对象的资料请关注编程网其它相关文章!

--结束END--

本文标题: Express框架reqres对象使用详解

本文链接: https://www.lsjlt.com/news/201212.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Express框架reqres对象使用详解
    目录IncomingMessageServerResponse请求对象 req响应对象设置状态码如何来快速测试这些属性和方法呢?下面给出一些示例代码目录结构安装依赖小结Express...
    99+
    2023-03-24
    Express框架req res对象 Express req res
  • Express框架Router Route Layer对象使用示例详解
    目录引言LayerRouteRouter方法统计两个 stack取出 stack 中 layer从 Router 到 layer 的路径Router.route 方法中的 dispa...
    99+
    2023-03-24
    Express使用Router Route Layer Express 对象
  • 一文解析Express框架view对象使用
    目录Expess View 从指定渲染引擎开始安装依赖从 res.render 函数开始View 的实现mustache 的render 方法的实现一个案例切图案例在 express...
    99+
    2023-03-10
    Express框架view对象 Express view
  • Express框架view对象如何使用
    本篇内容主要讲解“Express框架view对象如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Express框架view对象如何使用”吧!Expess View 从指定渲染引擎开始以 m...
    99+
    2023-07-05
  • Express框架req res对象如何使用
    这篇文章主要讲解了“Express框架req res对象如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Express框架req res对象如何使用”吧!Expre...
    99+
    2023-07-05
  • Express框架Router、Route和Layer对象如何使用
    今天小编给大家分享一下Express框架Router、Route和Layer对象如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了...
    99+
    2023-07-05
  • Express框架中_router对象数据结构如何使用
    这篇文章主要介绍了Express框架中_router对象数据结构如何使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Express框架中_router对象数据结构如何使用文章都会有所收获,下面我们一起来看看吧...
    99+
    2023-07-05
  • Node.js中Express框架的使用教程详解
    目录Express简介Express生成器1. 什么是Express生成器2. 安装Express生成器创建Express项目安装项目依赖运行Express项目Express目录结构...
    99+
    2022-11-13
  • Express框架详解app函数使用实例
    目录express 函数来源express 的其他输出app 方法中混入原型app 中挂载请求/响应对象app 中的原型app 对象上挂载方法app 初始化小结express 函数来...
    99+
    2023-03-03
    Express框架app函数 Express app
  • 配置ABP框架使用对象映射
    目录DTO和实体实体DTO麻烦的映射AutoMapper 集成IObjectMapper/ObjectMapper对象拓展DTO和实体 实体 实体是领域驱动设计(Domain Dri...
    99+
    2022-11-13
  • 如何在 Django 中使用 ASP 框架对象?
    Django 是一个非常流行的 Python Web 框架,它提供了许多功能和工具来帮助开发人员快速构建 Web 应用程序。但是,有时候我们需要在 Django 中使用 ASP 框架对象,以便更好地管理我们的 Web 应用程序。在本篇文章中...
    99+
    2023-11-11
    框架 对象 django
  • 如何在Java框架中使用Unix对象?
    Java是一种使用广泛的编程语言,拥有强大的功能和丰富的开发库。在Java中,使用Unix对象可以为我们的开发带来便利。本文将介绍如何在Java框架中使用Unix对象,以及如何使用Unix对象来处理文件和目录。同时,我们还将提供一些示例代码...
    99+
    2023-11-09
    框架 unix 对象
  • 如何配置ABP框架使用对象映射
    小编给大家分享一下如何配置ABP框架使用对象映射,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!DTO和实体实体实体是领域驱动设计(Domain Driven De...
    99+
    2023-06-29
  • 详解SQLAlchemy框架使用手册
    目录安装SQLAlchemy连接数据库创建数据表插入数据查询数据更新数据删除数据结论如果你正在学习Python编程语言,并且想要使用一个简单易用的ORM框架来操作数据库,那么SQLA...
    99+
    2023-05-19
    SQLAlchemy使用
  • pytest框架之fixture详细使用详解
    本人之前写了一套基于unnitest框架的UI自动化框架,但是发现了pytest框架之后觉得unnitest太low,现在重头开始学pytest框架,一边学习一边记录,和大家分享,话...
    99+
    2022-11-12
  • Go语言如何在NumPy框架中使用对象?
    NumPy是Python中一个重要的科学计算工具包,它提供了一个强大的多维数组对象和用于处理数组的函数库。但是,NumPy并不是Python中唯一的科学计算工具,有时候我们需要使用其他语言来解决一些问题,比如Go语言。那么,Go语言如何在...
    99+
    2023-08-21
    对象 numpy 框架
  • PythonFlask的request对象使用详解
    必知的Flask的request Flask Request对象 来⾃客户端⽹⻚的数据作为全局请求对象发送到服务器。为了处理请求数据,应该从Flask模块导 ⼊。 Request对象...
    99+
    2023-02-10
    Python Flask request对象 Flask request Python request
  • 详解python调度框架APScheduler使用
    最近在研究python调度框架APScheduler使用的路上,那么今天也算个学习笔记吧! # coding=utf-8 """ Demonstrates how to use the backgro...
    99+
    2022-06-04
    详解 框架 python
  • Android xUtils框架最全使用详解
    本文目录xUtils3简介xUtils使用方法使用前准备功能1:访问网络不带参数的网络请求带参数的请求功能2:加载网络图片功能3:框架注解布局文...
    99+
    2022-06-06
    xutils框架 xutils Android
  • Android Volley框架使用方法详解
    本文主要从两个方面对Android Volley框架的使用方法进行讲解,具体内容如下 一、网络请求 1.get方式请求数据 // 1 创建一个请求队列 RequestQue...
    99+
    2022-06-06
    volley框架 方法 volley Android
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作