1

My fetch() method for making api requests works only when inside getServerSideProps() method.

For example I have api call for fetching a customer cart (and it is inside getServerSideProps):

    const res = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + jwtToken
      }
    });

And it works fine, I get response from api with customer cart. But when I try to make that api call on a button click, and when I move that inside button click handle method, then I get firstly:

Access to fetch at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

After that when I set mode to 'no-cors', then I get this:

GET ... net::ERR_ABORTED 400 (Bad Request)

So how it is possible that when inside getServerSideProps, there are no any CORS issues and everything is good, but when works on a button click then I get CORS issue and after that there is that other 'Bad request' problem.

Denis2310
  • 939
  • 1
  • 15
  • 41

1 Answers1

1

Becuase by design browsers block the API request when the API response doesn't have Access-Control-Allow-Headers. But when you fetch the API inside getServerSideProps the the API request is made by Node.js server which doesn't check for Access-Control-Allow-Headers.

If you want to make this API request in browser then you can fix it by:

// If you can change the API code, here's an example to add the CORS headers in a netlify serverless function, this is the API response that I return from a serverless function 
   return {
      statusCode: 200,
      headers: {
        /* Required for CORS support to work */
        'Access-Control-Allow-Origin': '*', // you can add the domain names here or '*' will allow all domains
        /* Required for cookies, authorization headers with HTTPS */
        'Access-Control-Allow-Credentials': true
      },
      body: JSON.stringify({
        message: 'Hello from netlify'
      })
    }

or If your API backend is in Node.js and Express.js you can use cors npm package

if you don't have the access to change the API then try writing a wrapper API (or you can say a proxy API) that will make the API request and send it's response to you.

or If you just want the API request to happen for once only (on page load like componentDidMount) you can use the getServerSideProps.

For more detailed explanation on how to fix CORS error read How does Access-Control-Allow-Origin header work?

Viraj Singh
  • 1,951
  • 1
  • 17
  • 27
  • Thanks Viraj! So how to fix it? So the fix will be to add headers to api response or to api request? Do you think that other error 'Bad request' is also there because of CORS? – Denis2310 Aug 04 '21 at 08:35
  • 'Bad request' is just a genral error that is show in the browser console, which means the API request is failed for some reason, In your case the API request is failing because of CORS error. I've updated how to fix this issue. Consider marking it as accepted answer if it answers your question. – Viraj Singh Aug 04 '21 at 08:59