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

前端JS调用HaveIbeenpwned API遇401错误求助

问题原因与解决方案

为什么会返回401错误?

你使用的免费CORS代理corsproxy.io没有转发你设置的自定义请求头(即hibp-api-key)。这类免费代理通常仅转发标准HTTP请求头,自定义的API密钥头会被过滤,导致HIBP服务器根本未收到你的密钥,因此返回401未授权错误。

另外还有个核心问题:直接在前端代码中写入hibp-api-key会把密钥暴露给所有查看页面源码的人,HIBP官方明确禁止这种做法——密钥泄露后可能被他人滥用,导致你的API权限被封禁。

正确解决方法:用后端中转请求

最安全合规的方式是搭建自己的后端服务,由后端调用HIBP API,前端仅与自身后端交互。这样既规避了CORS问题,又能保护API密钥不被泄露。

示例后端代码(Node.js/Express)

const express = require('express');
const axios = require('axios');
const app = express();

// 处理跨域(生产环境建议限制具体域名)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET');
  next();
});

// 暴露给前端的查询接口
app.get('/check-breached', async (req, res) => {
  const targetEmail = req.query.email;
  if (!targetEmail) {
    return res.status(400).json({ error: '请提供邮箱地址' });
  }

  try {
    const hibpResponse = await axios.get(
      `https://haveibeenpwned.com/api/v3/breachedaccount/${encodeURIComponent(targetEmail)}`,
      {
        headers: {
          'hibp-api-key': '你的HIBP API密钥', // 密钥存于后端,不会暴露
          'user-agent': '你的应用名称/版本号' // 按HIBP要求填写用户代理
        }
      }
    );
    res.json(hibpResponse.data);
  } catch (err) {
    // 转发HIBP的错误信息
    res.status(err.response?.status || 500).json({
      error: err.response?.data || '请求HIBP API失败'
    });
  }
});

app.listen(3000, () => {
  console.log('后端服务运行在 http://localhost:3000');
});

修改后的前端调用代码

let breachResult = "";
const checkEmail = "test@gmail.com";

$.ajax({ 
  type: "GET", 
  url: `http://localhost:3000/check-breached?email=${encodeURIComponent(checkEmail)}`,
  success: function(result) { 
    breachResult = result;
    console.log("泄露记录:", breachResult);
  }, 
  error: function(xhr) { 
    console.log("请求失败:", xhr.responseJSON?.error || xhr.statusText);
  } 
});

额外注意事项

  • 生产环境中,后端的Access-Control-Allow-Origin不要设为*,应限制为你的前端域名,避免跨域滥用。
  • HIBP API有请求频率限制,后端可添加缓存机制减少重复请求。
  • 务必妥善保管HIBP API密钥,不要在前端代码、公开代码仓库中泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:20:24