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

React前端Axios遇net::ERR_CONNECTION_REFUSED,Node.js中请求正常?

解决Chrome扩展中Axios/fetch请求后端出现net::ERR_CONNECTION_REFUSED的问题

1. 先排查后端服务的可访问性

  • 确保Node后端服务绑定的地址不是localhost或127.0.0.1,改成0.0.0.0或公司内网IP,让Chrome扩展(作为独立进程)能正常访问服务。
  • 直接在Chrome地址栏输入http://myfully.qualifieddomainname.com:PORT/login,如果无法打开,先解决后端的网络可达性问题(比如端口是否开放、防火墙是否放行)。

2. 配置Chrome扩展的权限与内容安全策略

Manifest V3 配置

在manifest.json中添加主机权限和内容安全策略:

{
  "host_permissions": ["http://myfully.qualifieddomainname.com:PORT/*"],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none'; connect-src http://myfully.qualifieddomainname.com:PORT/"
  }
}

Manifest V2 配置

对应修改:

{
  "permissions": ["http://myfully.qualifieddomainname.com:PORT/*"],
  "content_security_policy": "script-src 'self'; object-src 'none'; connect-src http://myfully.qualifieddomainname.com:PORT/"
}

3. 后端配置CORS允许扩展访问

在Node后端安装并配置cors中间件,允许扩展的源请求:

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

// 替换为你的扩展ID,可在Chrome扩展管理页面开启开发者模式后查看
const extensionOrigin = 'chrome-extension://<你的扩展ID>';
app.use(cors({
  origin: extensionOrigin,
  credentials: true // 如果请求需要携带Cookie等凭证
}));

// 内部测试时可临时允许所有内网源(正式环境建议缩小范围)
// app.use(cors({ origin: /http:\/\/.*\.yourcompany\.com/ }));

4. 调整Chrome的不安全内容访问设置

由于使用HTTP协议,Chrome默认会限制非HTTPS的跨域请求,需手动添加例外:

  1. 打开chrome://settings/content/insecureContent
  2. 在"允许显示不安全内容"下,点击"添加",输入http://myfully.qualifieddomainname.com:PORT并保存

5. 代码优化建议

无需手动拼接URL编码的请求体,Axios可自动处理:

const getSwitchFlows = async () => {
  try {
    // 直接传对象,Axios会自动转为x-www-form-urlencoded格式
    const res = await axios.post('http://myfully.qualifieddomainname.com:PORT/login', {
      username: 'myusername',
      password: 'mypassword'
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    });

    if (res.data?.token) {
      const res2 = await axios.get('http://myfully.qualifieddomainname.com:PORT/api/v1/flows?ids=405', {
        headers: {
          Authorization: `Bearer ${res.data.token}`
        }
      });
      console.log(res2.data);
    }
  } catch (err) {
    console.error('请求失败:', err);
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:37:35