错误:HTTP 响应中缺少 Content-Range 标头

Kri*_*Max 3 javascript ruby-on-rails http-headers reactjs admin-on-rest

我正在设置 admin 休息,现在我在尝试获取数据时收到此错误,即使我从服务器收到了所有需要的数据:

The Content-Range header is missing in the HTTP Response. The simple REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?
Run Code Online (Sandbox Code Playgroud)

有没有办法在不更改 API 的情况下解决它?我正在根据教程进行授权,这是我的 app.js:

   if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' });
    }
    const token = localStorage.getItem('token');
    options.headers.set('Authorization', `Bearer  ${"token"}`);
    return fetchUtils.fetchJson(url, options);
}
const restClient = simpleRestClient('https://mywebsite.com', httpClient);

const App = () => (
<Admin restClient={restClient} authClient={authClient}>
    <Resource name="posts"  list={PostList}  edit={PostEdit} create={PostCreate}/>
        <Resource name="users" list={UserList}/>
    </Admin>
);
Run Code Online (Sandbox Code Playgroud)

Cha*_*mpR 11

问题不在于 React-App,而在于您的 REST 服务器。

就我而言,我使用的是 SimpleRestClient 并在他们的文档中读取

import simpleRestProvider from 'ra-data-simple-rest';
Run Code Online (Sandbox Code Playgroud)

注意:简单的 REST 客户端期望 API 在对 GET_LIST 调用的响应中包含 Content-Range 标头。该值必须是集合中的资源总数。这允许 admin-on-rest 知道总共有多少页资源,并构建分页控件。

Content-Range:posts 0-24/319 如果您的 API 作为 JS 代码在另一个域中,您需要使用 Access-Control-Expose-Headers CORS 标头将此标头列入白名单。

Access-Control-Expose-Headers:内容范围

因此,从您的服务器/REST 服务器,它必须返回(包含在响应中)两个标头

  1. Access-Control-Expose-Headers:内容范围
  2. 内容范围:帖子 0-24/319

在我的烧瓶服务器中,这就是我所做的

  1. 在您的回复中添加“内容范围”标题。

    response.headers.add('Access-Control-Expose-Headers', 'Content-Range')

  2. 添加标题“Content-Range”并为其分配一个范围值(通常以字节为单位)

    response.headers.add('Content-Range','bytes : 0-9/*')

最后:我注意到,当您的响应中省略任何一个标题时,您会收到相同的错误

错误:HTTP 响应中缺少 Content-Range 标头

确保您的服务器返回这些标头

'Access-Control-Expose-Headers', 'Content-Range' 或 'Content-Range','bytes : 0-9/*'

我希望这会有所帮助,因为这是我对 SO 问题的第一次回答