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

Chrome扩展调用Vercel托管的代理后端时出现401 Unauthorized错误求助

Chrome扩展调用Vercel托管的代理后端时出现401 Unauthorized错误求助

看起来你遇到的401问题大概率是Wiktionary的反爬策略在搞鬼,或者是Vercel部署时的一些配置细节没到位。我来给你梳理几个排查方向和解决方案:

  • 先搞定Wiktionary的请求头
    服务器端用node-fetch发起请求时,默认的User-Agent会被Wiktionary识别为非浏览器请求,直接拦下来。你需要给fetch请求加上模拟浏览器的请求头,同时处理好错误捕获:

    app.get('/proxy/:word', async (req, res) => {
      try {
        const word = req.params.word;
        // 替换成你实际要请求的Wiktionary地址,比如REST API或者页面URL
        const targetUrl = `https://en.wiktionary.org/api/rest_v1/page/definition/${encodeURIComponent(word)}`;
        
        const response = await fetch(targetUrl, {
          headers: {
            // 用一个常见的浏览器User-Agent伪装
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
          }
        });
    
        if (!response.ok) {
          throw new Error(`Wiktionary返回状态码: ${response.status}`);
        }
    
        const data = await response.json();
        res.json(data);
      } catch (err) {
        // 根据错误返回对应状态码,方便前端排查
        const statusCode = err.message.includes('401') ? 401 : 500;
        res.status(statusCode).send(err.message);
      }
    });
    

    要是你请求的是Wiktionary的网页HTML而不是API,把targetUrl换成https://en.wiktionary.org/wiki/${encodeURIComponent(word)}就行,记得一定要编码特殊字符(比如空格、特殊符号)。

  • 检查Vercel的CORS配置
    虽然你在Express里加了cors中间件,但Vercel平台本身有自己的HTTP头配置,可能会和你的Express设置冲突。建议在项目根目录新建一个vercel.json文件,添加专门的CORS规则:

    {
      "headers": [
        {
          "source": "/proxy/(.*)",
          "headers": [
            { "key": "Access-Control-Allow-Origin", "value": "chrome-extension://my-extension-id" },
            { "key": "Access-Control-Allow-Methods", "value": "GET, POST, OPTIONS" },
            { "key": "Access-Control-Allow-Headers", "value": "Content-Type, Authorization" }
          ]
        }
      ]
    }
    

    部署的时候Vercel会优先读取这个文件的配置,确保跨域请求被正确放行。

  • 确认扩展ID完全正确
    你在cors配置里写的chrome-extension://my-extension-id是不是你实际的扩展ID?打开Chrome的扩展管理页面(记得开启开发者模式),复制粘贴完整的ID,少一个字符或者大小写不对都会导致跨域验证失败,进而触发权限错误。

  • 排查前端请求的编码问题
    在Chrome扩展里发起请求时,一定要对请求的单词参数做URL编码,比如:

    // 扩展里的请求示例
    const searchWord = "apple pie";
    const encodedWord = encodeURIComponent(searchWord);
    fetch(`https://你的Vercel域名.vercel.app/proxy/${encodedWord}`)
      .then(res => {
        if (!res.ok) throw new Error(`代理返回状态码: ${res.status}`);
        return res.json();
      })
      .then(data => console.log('获取到的数据:', data))
      .catch(err => console.error('请求出错:', err));
    

    如果参数没编码,带空格或者特殊字符的请求会被Vercel或者Wiktionary识别为无效请求,可能返回401或者404。

备注:内容来源于stack exchange,提问作者M X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 11:54:39