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

Fetch API请求localhost:3000报错,URL协议不支持求解决方案

解决Fetch API请求localhost时的"URL scheme not supported"错误并获取数据列表

问题根源

你遇到的错误有两个核心原因:

  • Fetch API要求请求URL必须包含协议头(http/https),直接写localhost:3000会被浏览器识别为无协议的URL,导致不支持的错误。
  • 前端请求的路径是根路径/,但你的Express服务器只在/list路径下返回数据,路径不匹配。

修复步骤与代码修改

1. 修正Fetch请求的URL

将React组件中componentDidMount里的Fetch请求改为带协议头且匹配接口路径的完整URL,同时增加错误处理逻辑:

componentDidMount() {
  fetch("http://localhost:3000/list")
    .then((response) => {
      // 先校验请求是否成功
      if (!response.ok) {
        throw new Error('请求失败');
      }
      return response.json();
    })
    .then((list) => {
      console.log(list);
      // 获取数据后更新组件状态,用于后续渲染列表
      this.setState({ list });
    })
    .catch((error) => {
      // 捕获并输出请求错误,便于排查问题
      console.error('获取列表失败:', error);
    });
}

2. 启用列表渲染逻辑

取消注释render方法中的列表渲染代码,同时增加加载状态提示:

render() {
  return (
    <ul>
      {this.state.list ? this.state.list.map((item) => (
        <li key={item.id}>{item.name}</li>
      )) : <li>加载中...</li>}
    </ul>
  );
}

3. 确认服务器正常运行

确保你的Express服务器已启动(执行node 你的服务器文件名.js),控制台输出Server start即为服务正常运行状态。

完整修改后的React组件代码

import React, { Component } from "react";

export default class List extends Component {
  constructor(props) {
    super(props);

    this.state = {
      list: null,
    };
  }

  componentDidMount() {
    fetch("http://localhost:3000/list")
      .then((response) => {
        if (!response.ok) {
          throw new Error('请求失败');
        }
        return response.json();
      })
      .then((list) => {
        console.log(list);
        this.setState({ list });
      })
      .catch((error) => {
        console.error('获取列表失败:', error);
      });
  }

  render() {
    return (
      <ul>
        {this.state.list ? this.state.list.map((item) => (
          <li key={item.id}>{item.name}</li>
        )) : <li>加载中...</li>}
      </ul>
    );
  }
}

验证效果

  1. 启动Express服务器
  2. 运行React应用
  3. 页面会先显示"加载中...",2秒后服务器返回数据,页面自动渲染出Item1、Item2、Item3的列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:45:36