React admin-on-rest adding X-Total-Count
Asked Answered
P

2

6

I'm using admin-on-rest but getting an error when trying to connect to github api

Error:

The X-Total-Count header is missing in the HTTP Response. The jsonServer 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 X-Total-Count in the Access-Control-Expose-Headers header?

and

Warning: Missing translation for key: "The X-Total-Count header is missing in the HTTP Response. The jsonServer 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 X-Total-Count in the Access-Control-Expose-Headers header?"

I'm trying to add the X-Total-Count header but then got a new error

render() {

const httpClient = (url, options = {}) => {
  if (!options.headers) {
    options.headers = new Headers({Accept: 'application/json'});
  }
  // add your own headers here
  options.headers.set('X-Total-Count', '32');
  return fetchUtils.fetchJson(url, options);
}

const restClient = jsonServerRestClient('https://api.github.com', httpClient);

return (
  <Admin restClient={restClient}>
    <Resource name="users" list={PostList}/>
  </Admin>
);
}

Failed to load https://api.github.com/users?_end=10&_order=DESC&_sort=id&_start=0: Request header field x-total-count is not allowed by Access-Control-Allow-Headers in preflight response.

Pestilential answered 1/5, 2018 at 20:58 Comment(2)
Even though AOR needs this info in the header. It need not be part of the request. You need to attach it to the response manually.Ayers
Note: The jsonServer REST client expects the API to include a X-Total-Count header in the response to GET_LIST calls. The value must be the total number of resources in the collection. This allows admin-on-rest to know how many pages of resources there are in total, and build the pagination controls.Ferromagnetism
V
5

At your backend API function need to get X-Total-Count and set it to Response Header

Example:

exports.findAll = (req, res) => {
  var total = Data.countAll()// your count all function
  Data.findAll({ where: condition })
    .then(data => {
      res.set('Access-Control-Expose-Headers', 'X-Total-Count')
      res.set('X-Total-Count', total)
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving data."
      });
    });
};
Value answered 21/6, 2021 at 7:42 Comment(0)
C
3

As kunal pareek said, this header must be part of the response, not the request for this jsonRestClient.

You'll have to create a custom restClient specific to the github api. Please read https://marmelab.com/admin-on-rest/RestClients.html#writing-your-own-rest-client.

Chasteen answered 3/5, 2018 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.