0
votes

I've created a SSR/progressive nuxt project using create-nuxt-app.

I have two pages, each making an HTTP request to a backend API I manage. This HTTP request is performed from my nuxt page's async asyncData(ctx) method.

When I access any of these pages directly or reload the these pages, these HTTP requests work fine. Yet when I either click a <nuxt-link :to="/mypage" /> or hit the back button on my browser:

  1. An 'Origin' header is added to my HTTP request all of a sudden. I guess this is the browser doing this because my HTTP request is being made from my client-side JavaScript instead of nuxt's node server, right?

  2. The HTTP request is performed yet before the request can send a response, the new page is loaded immediately. A console error is shown: Access to XMLHttpRequest at 'http://localhost.myapi/foobar' from origin 'http://localhost.mynuxtapp' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This kind of makes sense because I set a breakpoint on my API and it doesn't even have a chance to respond with this proper header in the response.

  3. The page displays a nuxt "network error" message after clicking this <nuxt-link /> or going back in my browser due to the error message above.

So my question is:

It appears that nuxt's asyncData method (https://nuxtjs.org/guide/async-data) performs client side code execution. Is there a different method available to prevent this?

1

1 Answers

0
votes

Just add if (process.server) {} in your asyncData method, as shown here, to perform code only server side.