5.02 详细解读TypeScript中的 request 对象
在 TypeScript 中,request 对象通常指的是 HTTP 请求对象。这个对象包含了发送到服务器的请求的所有相关信息。以下是对 request 对象的详细解读:
- 基本属性:
interface Request {
method: string; // 请求方法(GET, POST, PUT, DELETE等)
url: string; // 请求的URL
headers: Headers; // 请求头
body: ReadableStream<Uint8Array> | null; // 请求体
mode: RequestMode; // 请求模式(cors, no-cors, same-origin)
credentials: RequestCredentials; // 凭证模式(omit, same-origin, include)
cache: RequestCache; // 缓存模式
redirect: RequestRedirect; // 重定向模式
referrer: string; // 请求的来源
referrerPolicy: ReferrerPolicy; // 引用策略
integrity: string; // 子资源完整性
keepalive: boolean; // 保持连接
signal: AbortSignal | null; // 用于中止请求的信号
}
- 请求头操作:
// 获取特定请求头
request.headers.get('Content-Type'): string | null;
// 设置请求头
request.headers.set('Authorization', 'Bearer token');
// 添加请求头
request.headers.append('Accept', 'application/json');
// 删除请求头
request.headers.delete('X-Custom-Header');
- 请求体操作:
请求体可以是多种格式,如 JSON、FormData、Blob 等。
// 创建带有JSON体的请求
const jsonRequest = new Request('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
});
// 创建带有FormData体的请求
const formData = new FormData();
formData.append('username', 'john');
formData.append('password', 'secret');
const formRequest = new Request('https://api.example.com/login', {
method: 'POST',
body: formData,
});
- 克隆请求:
- 在 Fetch API 中使用:
const request = new Request('https://api.example.com/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
},
});
fetch(request)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
- 在 Express. Js 中的 request 对象(服务器端):
在服务器端框架如 Express. Js 中,request 对象有不同的结构:
interface Request {
params: any; // 路由参数
query: any; // 查询字符串参数
body: any; // 请求体(需要body-parser中间件)
headers: IncomingHttpHeaders; // 请求头
cookies: any; // Cookies(需要cookie-parser中间件)
method: string; // HTTP方法
path: string; // 请求路径
protocol: string; // 协议(http或https)
ip: string; // 客户端IP地址
// ... 其他属性和方法
}
// 示例使用
app.get('/api/users/:id', (req: Request, res: Response) => {
const userId = req.params.id;
const token = req.headers['authorization'];
const queryParam = req.query.filter;
// ... 处理请求
});
- 在 Axios 中创建请求配置:
Axios 使用配置对象来定义请求,而不是 Request 对象:
import axios from 'axios';
const config: AxiosRequestConfig = {
method: 'post',
url: 'https://api.example.com/data',
headers: {
'Content-Type': 'application/json',
},
data: {
key: 'value',
},
};
axios(config)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
- 安全考虑:
在处理请求时,始终要考虑安全性: - 验证和清理输入数据 - 使用 HTTPS - 实施适当的 CORS 策略 - 保护敏感信息(如 API 密钥)
理解和正确使用 request 对象对于开发健壮和安全的 Web 应用程序至关重要。它允许你精确控制发送到服务器的请求,包括方法、头部、体和各种选项。在不同的环境(客户端、服务器端)和框架中,request 对象可能有不同的结构和用法,但基本概念是相似的。