Search code examples
javascriptnode.jsexpressmongoose

Error: The X-Total-Count header is missing in the HTTP Response. | React Admin


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?


Solution

  • 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);
      }
    });