Why is postman showing error message but react app not showing it?

Viewed 194

I am developing an API (AWS lambda function using nodejs). here I am checking if the files sent to API via HTTP POST are less than 2 MB. if they are more than that then I am raising an error.

import createError from "http-errors";

if (totalSize > sizeLimitInMB) {
    throw new createError.Forbidden(
      `Size of all the attachments combined should not exceed ${sizeLimitInMB} MB. The files you have submitted are ${totalSize} MB`
    );
  }

Now postman shows this error message correctly. But when I try to produce same situation using my react front end. I get this message instead

Access to XMLHttpRequest at 'MY_API_URL' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

an error occurred  Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

POST 'MY_API_URL' net::ERR_FAILED

I am not sure why CORS error, because it works if my files are less than 2 MB. my code in react component

try {
      await submit(id, data);
      setSaving(false);
      history.replace("/");
    } catch (error) {
      setSaving(false);
      console.error("an error occurred ", error);
    }

Why is the frontend not able to console log the same error message as postman? and this is not just for this particular size error. Any other errors I throw such as "Only owner can delete this file" or "Post with this ID not found" are also not displayed in my frontend but work perfectly well in postman

1 Answers

I was able to solve this issue by changing the order of middlewares in common middleware. I had a function common middleware that used to wrap the handler

export const handler = commonMiddleware(myHandler);

Earlier it was
export default (handler) =>
  middy(handler).use([
    httpJsonBodyParser(),
    httpEventNormalizer(),
    httpErrorHandler(),
    cors(),
  ]);

After
export default (handler) =>
  middy(handler).use([
    cors(),
    httpJsonBodyParser(),
    httpEventNormalizer(),
    httpErrorHandler(),
  ]);

and it worked

Related