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

WSL Ubuntu环境下React+Axios调用Express接口遇ERR_NETWORK错误

解决WSL环境下Vite React调用Express后端的Axios网络错误问题

1. 修正Express后端的监听地址

WSL环境中,若Express仅监听localhost或127.0.0.1,仅能在WSL内部访问,Windows主机无法直接连接。必须让后端监听0.0.0.0以对外暴露端口:

app.listen(3001, '0.0.0.0', () => {
  console.log('Server running on port 3001');
});

2. 使用WSL的实际IP地址发起请求

在WSL终端执行ip addr show eth0,找到inet字段后的IP(例如172.17.0.2),前端请求替换为该IP:

axios.get('http://172.17.0.2:3001/api/products')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

3. 检查Windows防火墙与端口转发

  • 打开Windows Defender防火墙高级设置,添加入站规则,允许Express使用的TCP端口(如3001)通过防火墙。
  • 若端口转发异常,可在Windows终端手动添加转发规则:
netsh interface portproxy add v4tov4 listenport=3001 listenaddress=0.0.0.0 connectport=3001 connectaddress=你的WSL_IP

4. 配置Vite代理简化请求(推荐)

在项目根目录的vite.config.js中添加代理配置,避免跨域和IP切换问题:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://你的WSL_IP:3001',
        changeOrigin: true,
      },
    },
  },
});

之后前端直接用相对路径请求:

axios.get('/api/products')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

5. 验证后端可访问性

先在Windows浏览器或终端用curl http://你的WSL_IP:3001/api/products测试,确认后端能正常返回数据,再排查前端Axios配置问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:00:56