0

I'm trying to fetch some data from a webservice like so:

async function request(path: string, args: RequestInit | undefined): Promise<Response> {
    const headers: RequestInit = {
        mode: "no-cors" as RequestMode,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    const url = `${ROOT_URL}/${path}?apiKey=${API_KEY}`
    const options = {
        ...args,
        ...headers,
    }

    const result = await fetch(url, options)
    return result;
}

try {

    const response = await request('my/endpoint', {
        method: 'GET',
    })

    console.log('received response: ')
    console.log(response)

    const result = await response.json();
    console.log(result)
    return Promise.resolve(result)

} catch(error) {

    console.log('error:')
    console.log(error)
    return Promise.reject(error)

}

When sending this request, I see the following error in the console:

[Log] SyntaxError: The string did not match the expected pattern. — imagesSlice.ts:110 (bundle.js, line 633)

Additionally, the body field of the response object is null.

However, if I curl the exact URL, or paste it into the browser, the response body contains the correct JSON, which is verifiable by jsonlint.

What could be failing here? And also how can I debug this?

I have tried using await response.text() to take a look at the response body, and this returns an empty string.

sak
  • 2,612
  • 24
  • 55
  • `no-cors` will prevent you from reading a body. `no-cors` is almost never what you want. This issue is so prevalent on stack overflow, I wrote a small article some time ago: https://evertpot.com/no-cors/ – Evert Mar 23 '23 at 09:41
  • Ah this makes sense. I am only using this as a crutch because cors is not working for me: https://stackoverflow.com/questions/75820001/how-do-i-enable-cors-for-an-api-gateway-api-using-cdk – sak Mar 23 '23 at 16:18
  • it doesn't do what you think it does – Evert Mar 23 '23 at 19:44

0 Answers0