skip to Main Content

I`m trying to fetch posts from "http://localhost:5001/posts".

I’m using react-admin but with my own api, this is the "dataprovider" for the frontend:

import jsonServerProvider from "ra-data-json-server";
const dataProvider = jsonServerProvider("http://localhost:5001");

on the backend this is my code:


const app = express();

// Middlewares
app.use(express.json());
app.use(cors());


// get posts
app.get("/posts", async (req, res) => {
  try {
    const posts = await Post.find();
    res.status(200).json(posts);
  } catch (error) {
    console.log(error);
  }
});

full error message:

Error: The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider 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?

How do I set the X-Total-Count header for the GET Request?

2

Answers


  1. In Express, you can specify headers on the response using the header method that’s on the res object.

    Try something along the lines of:

    app.get("/posts", async (req, res) => {
      try {
        const posts = await Post.find();
    
        res.header('Access-Control-Expose-Headers', 'X-Total-Count')
        res.header('X-Total-Count', posts.length)
        res.status(200).json(posts);
      } catch (error) {
        console.log(error);
      }
    });
    
    Login or Signup to reply.
  2.     // Backend
        let data : any = {};
        //...find()
        res.header('Access-Control-Expose-Headers', 'X-Total-Count')
        res.header('X-Total-Count', document.length)
        res.status(202).json(document); // Incorrect .json({ data })
    
        // Frontend custom data provider
        const apiUrl = 'http://localhost:4000/api/v1';
        const httpClient = fetchUtils.fetchJson;
        const dataProvider = {
          getList: (resource, params) => {
              const { page, perPage } = params.pagination;
              const { field, order } = params.sort;
              const query = {
                  sort: JSON.stringify([field, order]),
                  range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
                  filter: JSON.stringify(params.filter),
              };
              const url = `${apiUrl}/${resource}?${stringify(query)}`;
    
              return httpClient(url).then(({ headers, json }) => ({
                  //data: json,
                  data: json.map(resource => ({ ...resource, id: resource._id }) ),
                  //total: parseInt(headers.get('content-range').split('/').pop(), 10),
                  total: parseInt(headers.get('X-Total-Count'))
              }));
          }
        }

    If u like my case, u need to write your custom data provider

    Our topic may be repeated [https://stackoverflow.com/questions/57297317/the-response-to-get-list-must-be-like-data-but-the-received-data][1]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search