Express托管json-server后React-Admin getList响应格式错误排查
尝试从接入Express服务器的json-server获取数据时,遇到以下错误:
The response to 'getList' must be like { data : [...] }, but the received data is not an array. The dataProvider is probably wrong for 'getList' ra.notification.data_provider_error at validateResponseFormat (validateResponseFormat.ts:30:1) at useDataProvider.ts:109:1
相关配置代码
Express服务器及头信息配置
server.use(cors()); const allowCrossDomain = (req, res, next) => { res.header("Access-Control-Expose-Headers", "Content-Range"); res.header("Content-Range", "cakeData 0:20/*"); next(); }; server.use(allowCrossDomain); server.use("/api", jsonServer.router("api/db.json"));
db.json内容
{ "cakeData": [ { "id": 1, "imageurl": "https://images.unsplash.com/photo-1674991773078-12a3eab409b2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=627&q=80", "name": "cake", "description": "information about cake" }, { "id": 2, "imageurl": "https://images.unsplash.com/photo-1674991773078-12a3eab409b2?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=627&q=80", "name": "cake", "description": "information about cake" } ] }
React-Admin组件代码
<Admin basename="/admin" dataProvider={simpleRestProvider("http://localhost:3000/")} > <Resource name="cakeData" list={ProductList} create={CreateProduct} edit={EditProduct} /> </Admin>
原本单独使用带中间件的json-server时功能正常,但接入Express后出现上述错误。另外在React中配置了代理,将3000端口请求转发至5000端口。
核心问题
react-admin的simpleRestProvider期望列表接口返回数组或{ data: [...], total: number }格式的响应,但接入Express后,json-server的路由被挂载到/api路径下,而当前react-admin配置的请求根路径不包含/api,导致请求路径错误,获取到的响应不是预期的数组数据,从而触发格式校验错误。
解决步骤
修正react-admin的dataProvider根路径
将simpleRestProvider的base URL补充/api后缀,确保请求路径匹配Express中挂载的json-server路由:<Admin basename="/admin" dataProvider={simpleRestProvider("http://localhost:3000/api")} > <Resource name="cakeData" list={ProductList} create={CreateProduct} edit={EditProduct} /> </Admin>确认React代理配置有效性
确保React项目的代理配置正确转发/api路径到Express的5000端口,例如在package.json中配置:"proxy": "http://localhost:5000"配置后,React应用请求
/api/cakeData时会自动转发到http://localhost:5000/api/cakeData,匹配到json-server的正确接口。验证接口响应格式
直接访问http://localhost:5000/api/cakeData,确认返回的是cakeData数组。此时react-admin的simpleRestProvider会自动将数组适配为自身需要的{ data: [...] }格式,解决校验错误。检查响应头配置
通过浏览器开发者工具的Network标签,确认响应头包含Content-Range: cakeData 0:20/*,这是react-admin处理分页功能必需的配置,当前Express的中间件已正确设置,只需确保请求能触发该中间件即可。
内容的提问来源于stack exchange,提问作者Donny90

