需要 Scripting PRO
HttpResponse 类表示服务器对客户端请求的响应对象。
它定义了 HTTP 响应的状态码、响应体及头部信息,并提供多种便捷方法生成常见的标准响应(如 ok、notFound、internalServerError 等)。
此类通常与 HttpResponseBody 搭配使用,用于在服务器端返回文本、HTML、二进制数据或文件内容。
HttpResponse 的主要功能包括:
FileEntity 或 Data 对象直接构建响应体。statusCode: numberHTTP 响应状态码。
示例:
reasonPhrase: string状态码对应的原因短语(例如 "OK", "Not Found", "Internal Server Error" 等)。
示例:
headers(): Record<string, string>返回响应头的键值对对象。
示例:
static ok(body: HttpResponseBody): HttpResponse创建一个状态码为 200 OK 的响应。
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
body |
HttpResponseBody |
响应体对象,可通过 HttpResponseBody.text()、data()、html() 创建。 |
示例:
static created(): HttpResponse返回 201 Created 响应,表示资源已成功创建。
示例:
static accepted(): HttpResponse返回 202 Accepted 响应,表示请求已被接受但尚未处理完成。
示例:
static movedPermanently(url: string): HttpResponse返回 301 Moved Permanently 响应,用于永久重定向。
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
url |
string |
重定向目标 URL。 |
示例:
static movedTemporarily(url: string): HttpResponse返回 302 Moved Temporarily 响应,用于临时重定向。
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
url |
string |
重定向目标 URL。 |
示例:
static badRequest(body?: HttpResponseBody | null): HttpResponse返回 400 Bad Request 响应,表示请求格式错误或参数无效。
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
body |
HttpResponseBody? |
可选的错误消息内容。 |
示例:
static unauthorized(): HttpResponse返回 401 Unauthorized 响应,表示需要身份验证。
示例:
static forbidden(): HttpResponse返回 403 Forbidden 响应,表示禁止访问。
示例:
static notFound(): HttpResponse返回 404 Not Found 响应,表示请求的资源不存在。
示例:
static notAcceptable(): HttpResponse返回 406 Not Acceptable 响应,表示请求的内容类型不被支持。
示例:
static tooManyRequests(): HttpResponse返回 429 Too Many Requests 响应,表示请求过于频繁。
示例:
static internalServerError(): HttpResponse返回 500 Internal Server Error 响应,表示服务器内部错误。
示例:
static raw(statusCode: number, phrase: string, options?: { headers?: Record<string, string>; body?: Data | FileEntity } | null): HttpResponse创建一个自定义状态码与内容的原始响应。
参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
statusCode |
number |
HTTP 状态码。 |
phrase |
string |
原因短语。 |
options.headers |
Record<string, string> |
自定义响应头。 |
options.body |
Data | FileEntity |
响应体,可以是二进制数据或文件对象。 |
示例:
HttpResponseBody.text(text: string)返回文本响应体。
HttpResponseBody.html(html: string)返回 HTML 响应体。
HttpResponseBody.data(data: Data)返回二进制响应体。