Fetch API 无法加载 fileCUserswoshiDesktopP5p5JSONbirds.json。对于 CORS 请求,URL 方案必须是“htt

jsetc

1个回答

写回答

15158088293

2025-07-09 19:35

+ 关注

etc
etc

使用 Fetch API 发送请求时,如果目标文件位于本地计算机的文件系统中,例如在本地文件系统中的路径为 file:///C:/Users/woshi/Desktop/P5/p5/JSON/birds.JSon,那么在浏览器控制台中可能会出现以下错误信息:"Fetch API 无法加载 file:///C:/Users/woshi/Desktop/P5/p5/JSON/birds.JSon。对于 CORS 请求,URL 方案必须是“http”或“https”"。这是因为浏览器的安全策略要求在使用 Fetch API 发送跨域请求时,URL 方案必须是 "http" 或 "https",而不是 "file"。

为了解决这个问题,我们可以通过使用本地服务器来提供所需的 JSON 文件,并使用 "http" 或 "https" 方案的 URL 进行请求。以下是一个简单的案例代码,演示如何使用 Fetch API 从本地服务器获取 JSON 数据。

html

<!DOCTYPE html>

<html>

<head>

<Meta charset="UTF-8">

<title>Fetch API 示例</title>

</head>

<body>

<h1>使用 Fetch API 获取本地 JSON 数据</h1>

<script>

// 创建一个本地服务器

const http = require('http');

const fs = require('fs');

const server = http.createServer((req, res) => {

// 读取本地 JSON 文件

fs.readFile('C:/Users/woshi/Desktop/P5/p5/JSON/birds.JSon', 'utf8', (err, data) => {

if (err) {

res.writeHead(404, { 'Content-Type': 'text/plAIn' });

res.end('File not found');

} else {

res.writeHead(200, { 'Content-Type': 'application/JSon' });

res.end(data);

}

});

});

// 启动服务器并监听指定端口

server.listen(3000, 'localhost', () => {

console.log('Server is running on http://localhost:3000');

});

// 使用 Fetch API 获取本地服务器提供的 JSON 数据

fetch('http://localhost:3000')

.then(response => response.JSon())

.then(data => {

console.log(data);

// 在此处处理获取到的 JSON 数据

})

.catch(error => console.error(error));

</script>

</body>

</html>

案例代码和解决方案:

上述案例代码中,我们首先创建了一个本地服务器,使用 Node.JS 中的 http 模块和 fs 模块。在服务器的请求处理函数中,我们读取了指定的本地 JSON 文件,并将其作为响应返回给客户端。

接下来,我们在客户端使用 Fetch API 发送一个 GET 请求到本地服务器的地址 http://localhost:3000。在获取到响应后,我们使用 .JSon() 方法将响应体解析为 JSON 数据,并在控制台中打印出来。

通过这种方式,我们成功绕过了浏览器的安全限制,使用 Fetch API 获取了本地 JSON 数据。同时,我们还可以在服务器端进行一些必要的处理,例如对请求进行验证、添加响应头等操作。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号