Skip to main content

请求和响应

¥Requests and Responses

Strapi 后端服务器基于 相思木 。当你通过 REST API 发送请求时,上下文对象 (ctx) 会传递到 Strapi 后端的每个元素(例如 policiescontrollersservices)。

¥The Strapi back end server is based on Koa . When you send requests through the REST API, a context object (ctx) is passed to every element of the Strapi back end (e.g., policies, controllers, services).

ctx 包括 3 个主要对象:

¥ctx includes 3 main objects:

  • ctx.request 有关客户端发出 API 请求所发送的请求的信息,

    ¥ctx.request for information about the request sent by the client making an API request,

  • ctx.state 有关 Strapi 后端内请求状态的信息,

    ¥ctx.state for information about the state of the request within the Strapi back end,

  • ctx.response 有关服务器将返回的响应的信息。

    ¥and ctx.response for information about the response that the server will return.

提示

还可以使用 strapi.requestContext function. 代码从代码中的任何位置访问请求的上下文。

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

信息

除了以下文档中描述的概念和参数外,你还可以在 Koa 请求文档 Koa 路由文档 Koa 响应文档  中找到其他信息。

¥In addition to the concepts and parameters described in the following documentation, you might find additional information in the Koa request documentation , Koa Router documentation  and Koa response documentation .

Simplified Strapi backend diagram with requests and responses highlighted
The diagram represents a simplified version of how a request travels through the Strapi back end, with requests and responses highlighted. The backend customization introduction page includes a complete, interactive diagram.

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.ipsX-Forwarded-For 存在且 app.proxy 启用时,将返回 IP 数组,按从上游到下游的顺序排列。

例如,如果值为 "客户端、代理 1、代理 2",你将收到 ["client", "proxy1", "proxy2"] 数组。
Array
ctx.request.method请求方法(例如,GETPOST)。String
ctx.request.origin第一个 / 之前的 URL 部分。String
ctx.request.paramsURL 中发送的参数。

例如,如果内部 URL 是 /restaurants/:id,那么你在实际请求中替换 :id 的任何内容都可以通过 ctx.request.params.id 访问。
Object
ctx.request.path请求资源的路径,不包括查询参数。String
ctx.request.protocol正在使用的协议(例如,httpshttp)。String
ctx.request.query表带专用 查询参数Object
ctx.request.subdomainsURL 中包含的子域名。

例如域名为 tobi.ferrets.example.com,则值为以下数组:["ferrets", "tobi"]
Array
ctx.request.url所请求资源的路径和查询参数,不包括协议、域和端口。String
Differences between protocol, origin, url, href, path, host, and hostname :

给定发送到 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 provides a query object that gives access to Strapi query parameters. The following table lists available parameters with a short description and a link to the relevant REST API documentation section (see REST API parameters for more information):

范围描述类型
ctx.request.query
ctx.query
整个查询对象。Object
ctx.request.query.sort对响应进行排序 的参数StringArray
ctx.request.query.filters过滤响应 的参数Object
ctx.request.query.populate填充关系、组件或动态区域 的参数StringObject
ctx.request.query.fields仅选择与响应一起返回的特定字段 的参数Array
ctx.request.query.pagination参数 逐页浏览条目Object
ctx.request.query.publicationState参数 选择草稿和发布状态String
ctx.request.query.locale参数 选择一个或多个区域设置StringArray

ctx.state

ctx.state 对象可以访问 Strapi 后端内的请求状态,包括有关 userauthenticationroute 的特定值:

¥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.messageresponse.status 关联。
String
ctx.response.header
ctx.response.headers
随响应一起发送的标头。Object
ctx.response.length`Content-Length`  标头值(如果存在)作为数字,或者在可能的情况下从 ctx.body 推断出来;否则,返回 undefinedInteger
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`Last-Modified`  标头作为日期(如果存在)。DateTime
ctx.response.etag设置响应的 `ETag` ,包括封装的“s。
没有相应的 response.etag getter。
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);
},
};

示例:

¥Example:

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

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

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

Strapi 使用名为 异步本地存储  的 Node.js 功能使上下文在任何地方都可用。

¥Strapi uses a Node.js feature called AsyncLocalStorage  to make the context available anywhere.