5

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.

qaakmnd
  • 339
  • 2
  • 4
  • 18
  • 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. – kunal pareek May 02 '18 at 10:21
  • 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. – Kirill Husiatyn Sep 14 '18 at 13:06

2 Answers2

4

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."
      });
    });
};
Tuan Le Anh
  • 147
  • 7
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.

Gildas Garcia
  • 6,966
  • 3
  • 15
  • 29