Skip to content
← Back to rules

unicorn/prefer-response-static-json 风格

An auto-fix is available for this rule.

它的作用

强制使用 Response.json() 代替 new Response(JSON.stringify())

为什么这是不好的?

Response.json() 是创建 JSON 响应的一种更简洁且语义更清晰的方式。 它会自动设置正确的 Content-Type 头(application/json),并处理序列化, 使代码更具可维护性,且更不易出错。

示例

此规则的错误代码示例:

javascript
const response = new Response(JSON.stringify(data));
const response = new Response(JSON.stringify(data), { status: 200 });

此规则的正确代码示例:

javascript
const response = Response.json(data);
const response = Response.json(data, { status: 200 });

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "unicorn/prefer-response-static-json": "error"
  }
}
bash
oxlint --deny unicorn/prefer-response-static-json

参考资料