Skip to main content

请求与响应

🌐 Requests and Responses

Page summary:

Koa 的上下文(ctx)在每个 Strapi 端点中携带请求信息、状态和响应数据。本文档详细说明了 ctx.request、ctx.state 和 ctx.response,以及用于在任何地方访问上下文的辅助工具。

Strapi 后端服务器基于 Koa。当你通过 REST API 发送请求时,一个上下文对象(ctx)会传递给 Strapi 后端的每个元素(例如,policies、controllers、services)。

ctx 包含 3 个主要对象:

  • ctx.request 了解关于发起 API 请求的客户端发送的请求的信息,
  • ctx.state 了解有关请求在 Strapi 后端状态的信息,
  • 以及 ctx.response 获取有关服务器将返回的响应的信息。
Tip

请求的上下文也可以通过代码中的任何位置使用 strapi.requestContext 函数 访问。

🌐 The request's context can also be accessed from anywhere in the code with the strapi.requestContext function.

Info

除了以下文档中描述的概念和参数外,你可能还会在 Koa request documentation、 Koa Router documentation 和 Koa response documentation中找到额外的信息。

Simplified Strapi backend diagram with requests and responses highlighted
该图表示请求在 Strapi 后端传输的简化版本,并突出了请求和响应。后端自定义介绍页面包括一个完整的、 交互式图表。

ctx.request​

ctx.request 对象包含以下参数:

🌐 The ctx.request object contains the following parameters:

参数描述类型
ctx.request.body正文的解析版本。Object
ctx.request.files随请求发送的文件。Array
ctx.request.headers随请求发送的头信息。Object
ctx.request.hostURL 的主机部分,包括端口。String
ctx.request.hostnameURL 的主机部分,不包括端口。String
ctx.request.href请求资源的完整 URL,包括协议、域名、端口(如果指定)、路径和查询参数。String
ctx.request.ip发送请求的人的IP。String
ctx.request.ips当 X-Forwarded-For 存在并且 app.proxy 启用时,将返回一个 IP 数组,按从上游到下游的顺序排列。

例如,如果值为 "client, proxy1, proxy2",你将收到 ["client", "proxy1", "proxy2"] 数组。
Array
ctx.request.method请求方法(例如,GET、POST)。String
ctx.request.origin第一个 / 之前的 URL 部分。String
ctx.request.params在URL中发送的参数。

例如,如果内部URL是 /restaurants/:id,在实际请求中替换 :id 的任何内容都可以通过 ctx.request.params.id 访问。
Object
ctx.request.path请求资源的路径,不包括查询参数。String
ctx.request.protocol使用的协议(例如,https 或 http)。String
ctx.request.queryStrapi特定的查询参数。Object
ctx.request.subdomains包含在URL中的子域名。

例如,如果域名是 tobi.ferrets.example.com,则值为以下数组:["ferrets", "tobi"]。
Array
ctx.request.url请求资源的路径和查询参数,不包括协议、域名和端口。String
协议、来源、URL、href、路径、主机和主机名之间的区别:

对于发送到 https://example.com:1337/api/restaurants?id=123 URL 的 API 请求,ctx.request 对象的不同参数返回如下内容:

🌐 Given an API request sent to the https://example.com:1337/api/restaurants?id=123 URL, here is what different parameters of the ctx.request object return:

参数返回值
ctx.request.hrefhttps://example.com:1337/api/restaurants?id=123
ctx.request.protocolhttps
ctx.request.hostlocalhost:1337
ctx.request.hostnamelocalhost
ctx.request.originhttps://example.com:1337
ctx.request.url/api/restaurants?id=123
ctx.request.path/api/restaurants

ctx.request.query​

ctx.request 提供了一个 query 对象,用于访问 Strapi 查询参数。下表列出了可用参数、简短描述以及相关 REST API 文档部分的链接(更多信息请参见 REST API 参数):

参数描述类型
ctx.request.query
ctx.query
整个查询对象。Object
ctx.request.query.sort用于 排序响应 的参数String 或 Array
ctx.request.query.filters用于筛选响应的参数Object
ctx.request.query.populate用于填充关联、组件或动态区域的参数String 或 Object
ctx.request.query.fields仅选择要随响应返回的特定字段 的参数Array
ctx.request.query.pagination用于翻页浏览条目的参数Object
ctx.request.query.publicationState参数用于选择草稿和发布状态String
ctx.request.query.locale参数,用于选择一个或多个语言环境String 或 Array

ctx.state​

ctx.state 对象提供对 Strapi 后端请求状态的访问,包括关于 用户、认证、路由 的具体值:

🌐 The ctx.state object gives access to the state of the request within the Strapi back end, including specific values about the user, authentication, route:

参数描述类型
ctx.state.isAuthenticated返回当前用户是否以任何方式经过身份验证。Boolean

ctx.state.user​

ctx.state.user 对象提供对执行请求的用户信息的访问,并包括以下参数:

🌐 The ctx.state.user object gives access to information about the user performing the request and includes the following parameters:

参数描述类型
ctx.state.user用户的信息。只填写一个关系。Object
ctx.state.user.role用户的角色Object

ctx.state.auth​

ctx.state.auth 对象提供与身份验证相关的信息访问,包括以下参数:

🌐 The ctx.state.auth object gives access to information related to the authentication and includes the following parameters:

参数描述类型
ctx.state.auth.strategy当前使用的认证策略的信息(用户与权限插件 或 API 令牌)Object
ctx.state.auth.strategy.name当前使用的策略名称String
ctx.state.auth.credentials用户的凭证String

ctx.state.route​

ctx.state.route 对象提供对与当前路由相关的信息的访问,包括以下参数:

🌐 The ctx.state.route object gives access to information related to the current route and includes the following parameters:

参数描述类型
ctx.state.route.method用于访问当前路由的方法。String
ctx.state.route.path当前路由的路径。String
ctx.state.route.config关于当前路由的配置信息。Object
ctx.state.route.handler当前路由的处理程序(控制器)。Object
ctx.state.route.info关于当前路由的附加信息,例如 apiName 和 API 请求类型。Object
ctx.state.route.info.apiName所使用 API 的名称。String
ctx.state.route.info.type所使用 API 的类型。String

ctx.response​

ctx.response 对象提供对服务器将返回的响应相关信息的访问,并包括以下参数:

🌐 The ctx.response object gives access to information related to the response that the server will return and includes the following parameters:

参数描述类型
ctx.response.body响应的内容。Any
ctx.response.status响应的状态码。Integer
ctx.response.message响应的状态消息。

默认情况下,response.message 与 response.status 相关联。
String
ctx.response.header
ctx.response.headers
随响应发送的头信息。Object
ctx.response.length当存在时,将 <ExternalLink to="https://web.nodejs.cn/en-US/docs/Web/HTTP/Headers/Content-Length" text="Content-Length"/> 头的值作为数字,或在可能时从 ctx.body 推断;否则,返回 undefined。Integer
ctx.response.redirect
ctx.response.redirect(url, [alt])
执行对 URL 的 302 重定向。字符串 “back” 被特殊处理以提供 Referrer 支持;当 Referrer 不存在时,使用 alt 或 “/”。

示例: ctx.response.redirect('back', '/index.html');
Function
ctx.response.attachment

ctx.response.attachment([filename], [options])
将 `Content-Disposition` 头设置为 "attachment",以提示客户端进行下载。可选地指定下载文件名和一些 options。Function
ctx.response.type`Content-Type` 头,不包含诸如 "charset" 之类的参数。String
ctx.response.lastModified将 <ExternalLink to="https://web.nodejs.cn/en-US/docs/Web/HTTP/Headers/Last-Modified" text="Last-Modified"/> 头作为日期,如果它存在的话。DateTime
ctx.response.etag设置响应的 `ETag`,包括封装的 s.
没有对应的 response.etag 获取器。
String

在任何地方访问请求上下文​

🌐 Accessing the request context anywhere

Strapi 公开了一种从代码中的任何位置访问当前请求上下文的方法(例如生命周期函数)。

🌐 Strapi exposes a way to access the current request context from anywhere in the code (e.g. lifecycle functions).

你可以按如下方式访问该请求:

🌐 You can access the request as follows:

const ctx = strapi.requestContext.get();

你应该只在 HTTP 请求上下文中调用的函数内部使用它。

🌐 You should only use this inside of functions that will be called in the context of an HTTP request.

// correct

const service = {
myFunction() {
const ctx = strapi.requestContext.get();
console.log(ctx.state.user);
},
};

// incorrect
const ctx = strapi.requestContext.get();

const service = {
myFunction() {
console.log(ctx.state.user);
},
};

示例:

./api/test/content-types/article/lifecycles.js

module.exports = {
beforeUpdate() {
const ctx = strapi.requestContext.get();

console.log('User info in service: ', ctx.state.user);
},
};
Note

Strapi 使用 Node.js 的一个名为 AsyncLocalStorage 的功能来使上下文在任何地方都可用。

Tip

有关在插件中从管理面板发起经过身份验证的 HTTP 请求,请参见 Admin Panel API: 获取客户端。

🌐 For making authenticated HTTP requests from the admin panel in plugins, see Admin Panel API: Fetch client.