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

Fetch请求localhost接口报URL scheme不支持错误如何解决

报错根因

Fetch请求抛出URL scheme "localhost" is not supported错误,核心原因是传入的请求地址缺少协议前缀。Postman测试接口时会自动补全缺失的http://协议,所以能正常发起请求;但浏览器原生Fetch API不会做这类自动补全,会直接判定localhost:3000/send为非法URL,拒绝发起请求。

修复方案

1. 补全请求地址的协议头

本地开发环境直接在地址前加http://前缀即可,修改后的前端请求代码:

const getData = async () => {
    // 地址前补充http://协议前缀
    const response = await fetch("http://localhost:3000/send", {
      method: "GET",
    });
    const data = await response.json();
    console.log(data);
};
getData();

2. 处理本地开发跨域问题

如果你的前端页面不是通过http://localhost:3000打开(比如用VS Code Live Server跑在5500端口、其他本地静态服务端口),补全地址后还会触发浏览器跨域拦截,需要在Node.js Express后端做CORS配置:

  • 安装cors依赖
npm install cors
  • 在Express入口文件中引入并启用cors中间件,同时可以删掉原有接口里冗余的await逻辑,参考代码如下:
const express = require('express');
const cors = require('cors');
const app = express();

// 允许所有跨域请求,本地开发场景足够使用
app.use(cors());

app.get("/send", async (req, res) => {
  const products = await Product.find();
  // 原代码中products = await products是冗余逻辑,无实际作用可直接删除
  res.send(products);
});

app.listen(3000, () => {
  console.log('后端服务已启动在3000端口');
});

修改完成后重启Node.js后端服务,刷新前端页面即可正常获取接口返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 23:15:40