React.js中如何从同源服务请求目录内的JSON文件数据?
需求可行性结论
该需求完全可以实现。因为你的前端项目和请求目标地址是同源(协议、域名、端口完全一致),不存在跨域限制,可直接请求静态目录下的JSON文件。
具体操作步骤
1. 放置JSON文件到静态资源目录
- 如果你使用Create React App/Vite搭建的React项目,将需要访问的JSON文件放到项目根目录的
public文件夹下,可按需创建子目录分类存放。
示例:创建public/api/user.json,写入测试内容:
{ "id": 1, "username": "test_user", "email": "test@example.com" }
2. 在React组件中发起请求
你可以选择原生fetchAPI或者第三方请求库axios完成请求,两种方式的示例如下:
方式1:使用原生fetch API
import { useEffect, useState } from 'react'; function DemoPage() { const [userData, setUserData] = useState(null); // 组件挂载时发起请求 useEffect(() => { // 路径直接写public目录下的相对路径即可,无需补全完整域名 fetch('/api/user.json') .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then(data => setUserData(data)) .catch(error => console.error('错误信息:', error)); }, []); return ( <div> {userData ? ( <div> <p>用户名:{userData.username}</p> <p>邮箱:{userData.email}</p> </div> ) : <p>数据加载中...</p>} </div> ); } export default DemoPage;
方式2:使用axios请求库
- 先安装axios依赖:
npm install axios - 组件代码示例:
import { useEffect, useState } from 'react'; import axios from 'axios'; function DemoPage() { const [userData, setUserData] = useState(null); useEffect(() => { axios.get('/api/user.json') .then(response => setUserData(response.data)) .catch(error => console.error('错误信息:', error)); }, []); return ( <div> {userData ? ( <div> <p>用户名:{userData.username}</p> <p>邮箱:{userData.email}</p> </div> ) : <p>数据加载中...</p>} </div> ); } export default DemoPage;
注意事项
- 不要将JSON文件存放在
src目录下,该目录下的文件不会被作为静态资源暴露,请求会返回404 - 路径填写直接使用
public目录下的相对路径即可,后续项目部署到其他域名时无需修改请求路径 - 启动项目后访问
http://localhost:3000,即可正常拿到JSON数据
内容的提问来源于stack exchange,提问作者Ritik Joshi
相关产品推荐
相关产品推荐

