You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ESLint阻止从UI调用特定大响应量API?

如何用ESLint拦截特定危险API的调用?

当然可以实现!你可以通过自定义ESLint规则来精准检测并禁止调用/api/hugeResponse这个会导致浏览器崩溃的API,让团队成员在写出这类代码时立刻得到错误提示。下面是具体的实现步骤:

1. 创建自定义ESLint规则

ESLint的规则基于抽象语法树(AST)分析代码,我们需要编写一个规则来识别$http调用中指向目标路由的配置。

在项目中创建一个存放自定义规则的目录(比如eslint-rules),然后新建no-huge-response-api.js文件,写入以下代码:

module.exports = {
  meta: {
    type: "problem",
    docs: {
      description: "禁止调用会导致浏览器崩溃的/api/hugeResponse API",
      recommended: true,
    },
    messages: {
      forbiddenApi: "禁止调用/api/hugeResponse API:该接口返回超大响应数据,浏览器调用会崩溃,请使用CLI调用或优化接口逻辑",
    },
  },
  create(context) {
    return {
      // 监听所有函数调用节点
      CallExpression(node) {
        // 检查是否是this.$http的调用
        const isHttpCall = node.callee.type === "MemberExpression" &&
                          node.callee.object.type === "ThisExpression" &&
                          node.callee.property.name === "$http";

        if (!isHttpCall) return;

        // 获取$http的第一个参数(请求配置对象)
        const requestConfig = node.arguments[0];
        if (!requestConfig || requestConfig.type !== "ObjectExpression") return;

        // 查找配置中的url属性
        const urlProp = requestConfig.properties.find(prop => 
          prop.key.type === "Identifier" && prop.key.name === "url"
        );

        // 检查url值是否为目标路由
        if (urlProp?.value.type === "Literal" && urlProp.value.value === "api/hugeResponse") {
          // 在url值的位置抛出错误
          context.report({
            node: urlProp.value,
            messageId: "forbiddenApi",
          });
        }
      },
    };
  },
};

2. 配置ESLint使用自定义规则

在项目的.eslintrc.js(或对应的ESLint配置文件)中,添加自定义规则的引用:

module.exports = {
  // 其他基础配置(比如环境、解析器等)
  env: {
    browser: true,
    es2021: true,
    angular: true, // 如果你用的是Angular,需要开启这个环境
  },
  rules: {
    // 启用自定义规则,设为error级别会直接阻断代码提交或在IDE中报错
    "no-huge-response-api": "error",
  },
  // 指定自定义规则的目录
  rulesDirectory: ["./eslint-rules"],
};

3. 测试效果

现在当你写出示例中的代码时,ESLint会在第10行的"api/hugeResponse"字符串位置抛出错误,提示开发者禁止调用该API。

扩展优化

如果后续有更多类似的危险API,你可以把路由列表抽成一个数组,规则中检查url值是否在数组内,这样扩展性更强:

// 在规则的create函数内定义危险路由列表
const forbiddenRoutes = ["api/hugeResponse", "api/anotherLargeResponse"];

// 然后修改检查逻辑
if (urlProp?.value.type === "Literal" && forbiddenRoutes.includes(urlProp.value.value)) {
  context.report({
    node: urlProp.value,
    messageId: "forbiddenApi",
  });
}

内容的提问来源于stack exchange,提问作者scipper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:43