Skip to content
← Back to rules

unicorn/prefer-response-static-json Style

💡 A suggestion 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 });

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/prefer-response-static-json": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-response-static-json": "error",
  },
});
bash
oxlint --deny unicorn/prefer-response-static-json

版本

此规则于 v1.29.0 添加。

参考资料