How to solve JSON.parse Error from Vue Apollo Client with fetchOptions: {mode: 'no-cors'}

578 Views Asked by At

When using the Apollo client to fetch data, I'm getting the Error from the Apollo client: 'Network error: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'. (With Firefox)

enter image description here

With Chrome the Error message is a bit different:

>  Error: Network error: Unexpected end of JSON input at new ApolloError (webpack-internal:///./node_modules/apollo-client/bundle.esm.js:80:28) at eval (webpack-internal:///./node_modules/apollo-client/bundle.esm.js:1178:43)

Maybe it's Important to notice that Mutations are working.

In the main.ts file I'm using:

 const defaultClient = new ApolloClient({
  link: createHttpLink({
    uri: ` MY URL`,
    fetchOptions: {
      mode: 'no-cors',
          },
  }),
  cache: new InMemoryCache(),
});

I'm Using Vue3 with: apollo-composable": "^4.0.0-alpha.16"

Here are the headers:

enter image description here

When looking at the browser console in the Network Monitors Response tab, I'm getting a Status 200 POST with a valid JSON object: (I checked it with a JSON format validator... It's valid JSON)

enter image description here

So what really seems strange to me is that I'm getting back a valid JSON Object according to the response, but Apollo is giving me the JSON.parse error.

One thing I noticed is that when sending the Apollo request with mode: 'no-cors', the request headers Content-Type is 'text/plain' and when setting mode:'cors' the Content-Type is 'application/json'.

With mode:'cors' everything works fine. No errors.

I did some research and found out that with 'no-cors' the Content-Type 'application/json' is not allowed. But I don't know if that is causing the error. Also want to mention that mode:'no-cors' is needed from the backend requirements.

Headers when setting mode: 'cors' option:

enter image description here

Thanks a lot for helping :)

1

There are 1 best solutions below

0
On

fetch(..., {mode: "no-cors"}) performs the request but is not able to access the response if the request is cross-origin. In other words,

fetch(..., {mode: "no-cors"}).then(r=>r.body)

resolves to null. This explains the "unexpected end of data".

If you leave out the mode option, a CORS request will be made, and this will succeed if the server that you call sets the Access-Control-Allow-* headers.