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

React搭建简单admin panel时报TypeError: headers is undefined错误求助

错误原因

  • 你在httpClient方法中处理fetchUtils.fetchJson的返回结果时,仅返回了{ data: json }结构,丢弃了原返回值中包含的headers、status等必要字段。react-admin的simpleRestProvider依赖返回的headers信息处理分页、资源计数等逻辑,读取不到headers就会触发该类型错误。
  • 额外说明:Access-Control-Allow-Origin是服务端返回的响应头,不需要在客户端请求头中设置,这段代码属于冗余配置。

修复方案

调整fetchUtils.fetchJson的回调逻辑,保留原返回的所有字段,仅替换需要修改的data字段即可。

修正后的完整代码

import * as React from "react";

import { fetchUtils, Admin, Resource, ListGuesser } from 'react-admin';
import simpleRestProvider from 'ra-data-simple-rest';


const apiUrl = 'https://my-api';
const authToken =  "zvxvzx";

const httpClient = (url, options = {}) => {
  if (!options.headers) {
      options.headers = new Headers({ Accept: 'application/json' });
  }
  options.headers.set('Authorization', authToken);
  return fetchUtils.fetchJson(url, options).then((res) => ({ 
    ...res,
    data: res.json 
  }));
};

const dataProvider = simpleRestProvider(apiUrl, httpClient);

const App = () => (
  <Admin dataProvider={dataProvider} >
    <Resource name="requests" list={ListGuesser} />
  </Admin>
);

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:27:00