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> ); } }
验证效果
- 启动Express服务器
- 运行React应用
- 页面会先显示"加载中...",2秒后服务器返回数据,页面自动渲染出Item1、Item2、Item3的列表。
内容的提问来源于stack exchange,提问作者intern
相关产品推荐
相关产品推荐

