广告
返回顶部
首页 > 资讯 > 精选 >Express框架req res对象如何使用
  • 694
分享到

Express框架req res对象如何使用

2023-07-05 16:07:42 694人浏览 泡泡鱼
摘要

这篇文章主要讲解了“Express框架req res对象如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Express框架req res对象如何使用”吧!Expre

这篇文章主要讲解了“Express框架req res对象如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Express框架req res对象如何使用”吧!

    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>    <h3>欢迎来到 Home 页面</h3></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")); // Warning201 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框架req res对象如何使用”的内容了,经过本文的学习后,相信大家对Express框架req res对象如何使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

    --结束END--

    本文标题: Express框架req res对象如何使用

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

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

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

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

    下载Word文档
    猜你喜欢
    • Express框架req res对象如何使用
      这篇文章主要讲解了“Express框架req res对象如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Express框架req res对象如何使用”吧!Expre...
      99+
      2023-07-05
    • Express框架view对象如何使用
      本篇内容主要讲解“Express框架view对象如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Express框架view对象如何使用”吧!Expess View 从指定渲染引擎开始以 m...
      99+
      2023-07-05
    • Express框架reqres对象使用详解
      目录IncomingMessageServerResponse请求对象 req响应对象设置状态码如何来快速测试这些属性和方法呢?下面给出一些示例代码目录结构安装依赖小结Express...
      99+
      2023-03-24
      Express框架req res对象 Express req res
    • Express框架Router、Route和Layer对象如何使用
      今天小编给大家分享一下Express框架Router、Route和Layer对象如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了...
      99+
      2023-07-05
    • 一文解析Express框架view对象使用
      目录Expess View 从指定渲染引擎开始安装依赖从 res.render 函数开始View 的实现mustache 的render 方法的实现一个案例切图案例在 express...
      99+
      2023-03-10
      Express框架view对象 Express view
    • Express框架中_router对象数据结构如何使用
      这篇文章主要介绍了Express框架中_router对象数据结构如何使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Express框架中_router对象数据结构如何使用文章都会有所收获,下面我们一起来看看吧...
      99+
      2023-07-05
    • Express框架Router Route Layer对象使用示例详解
      目录引言LayerRouteRouter方法统计两个 stack取出 stack 中 layer从 Router 到 layer 的路径Router.route 方法中的 dispa...
      99+
      2023-03-24
      Express使用Router Route Layer Express 对象
    • Node.js 中如何使用Express框架
      这期内容当中小编将会给大家带来有关Node.js 中如何使用Express框架,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Node.js Express 框架Expre...
      99+
      2022-10-19
    • Express框架app函数如何使用
      本篇内容主要讲解“Express框架app函数如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Express框架app函数如何使用”吧!express 函数来源首先要搞明白 express...
      99+
      2023-07-05
    • Node第三方框架Express如何使用
      这篇文章主要讲解了“Node第三方框架Express如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Node第三方框架Express如何使用”吧!1....
      99+
      2022-10-19
    • 如何在 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
    • Go语言如何在NumPy框架中使用对象?
      NumPy是Python中一个重要的科学计算工具包,它提供了一个强大的多维数组对象和用于处理数组的函数库。但是,NumPy并不是Python中唯一的科学计算工具,有时候我们需要使用其他语言来解决一些问题,比如Go语言。那么,Go语言如何在...
      99+
      2023-08-21
      对象 numpy 框架
    • 如何使用Go语言对象对NumPy框架进行优化?
      NumPy是Python科学计算中最重要的库之一,它提供了高效的数组和矩阵运算,是许多数据科学家和研究人员必不可少的工具。然而,NumPy在处理大规模数据时,性能可能会受到限制。在本文中,我们将介绍如何使用Go语言对象对NumPy框架进行...
      99+
      2023-08-21
      对象 numpy 框架
    • 配置ABP框架使用对象映射
      目录DTO和实体实体DTO麻烦的映射AutoMapper 集成IObjectMapper/ObjectMapper对象拓展DTO和实体 实体 实体是领域驱动设计(Domain Dri...
      99+
      2022-11-13
    • Django 和 ASP 框架对象:如何选择正确的框架?
      在开发 Web 应用程序时,选择正确的框架是至关重要的。框架可以帮助你加快开发速度,减少代码错误,提高应用程序的可维护性。Django 和 ASP 是两个流行的框架,它们都有自己的优缺点。在本文中,我们将比较 Django 和 ASP 框...
      99+
      2023-11-11
      框架 对象 django
    • Java框架中,Unix对象如何实现?
      Java作为一种强大的编程语言,已经成为许多企业和开发者的首选。在Java应用程序开发中,框架的使用是非常常见的。Unix对象是Java框架中的一个重要概念,下面我们来探讨一下Java框架中Unix对象如何实现。 Unix对象是一种用于描述...
      99+
      2023-11-09
      框架 unix 对象
    • 你知道如何使用 Spring 框架来管理 ASP 对象吗?
      Spring 框架是一种流行的 Java 开发框架,它提供了一种简单的方法来管理 ASP 对象。在本文中,我们将探讨如何使用 Spring 框架来管理 ASP 对象,并提供一些演示代码。 ASP(Active Server Pages)是一...
      99+
      2023-10-23
      对象 unix spring
    • 如何在Go中使用对象和函数来构建框架?
      Go 是一种非常流行的编程语言,其简洁、高效的特性让它在 Web 开发、云计算、网络编程等方面得到广泛应用。在使用 Go 编写应用程序时,构建框架是一个非常重要的环节。本文将介绍如何在 Go 中使用对象和函数来构建框架,让你的应用程序更加灵...
      99+
      2023-11-02
      对象 函数 框架
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作