#CORS Error

43 messages · Page 1 of 1 (latest)

fervent gorge
#

my react app does not fetch data becuse of CORS error:
1 of my examples

getOne: async (resource, params) => {
    const url = `${apiUrl}/${resource}/${params.id}`
    return fetch(url, {
      method: 'GET',
      headers: {'Access-Control-Allow-Origin': '*'}
    })
    .then(data => data.json())
    .then(response => {
        // console.log(response);
        return { data: response}})
      // .then(data => console.log(data))
      .catch(err => console.error(err));
  },

help me

mild palm
#

see pinned messages in #help-chat. you maybe able to get away with a proxy, but you really need to understand CORS. so, do some reading.

fervent gorge
#

i did not find anything relative

fervent gorge
#

@mild palm By the way, this error appears only if i build and run in network

#

if i run locally, then everything works fine

cobalt jay
#

(unrelated: Never use .then. You already have an async function, write your code with await)

mild palm
#

the two links I pasted tell you how to deal with it for a local development environment

fervent gorge
fervent gorge
fervent gorge
cobalt jay
#

What's your current server code?

fervent gorge
#

I can rewrite 1 more time just in case

fervent gorge
#

i might be dumb

#
 async function fetchJSON (url, { headers = {}, ...init } = {}) {
  const response = await fetch(url, {
    ...init,
    headers: {
      ...headers,
      accept: "application/json",
    }
  });

  if (!response.ok)
    throw new Error(`Request at ${url} failed`);

  return response.json();
}
#

Should i put those after accept:"application/json"?

cobalt jay
#
fetchJSON(localUrl, { headers: {
  "access-control-request-private-network": true
} })```
fervent gorge
cobalt jay
#

That's absolutely not in the same part

#

Don't touch the definition of fetchJSON

#

But call it with the extra header

fervent gorge
#

why do you use true instead of "true" ?

cobalt jay
#

No, the allow must be server-side

cobalt jay
fervent gorge
cobalt jay
#

The client should make this fetch request like this, yes

#

Then the server must have additional code (Agoknee's links probably show that)

fervent gorge
cobalt jay
#

Do you know the difference between a definition and a call?

#

We never touched the definition

fervent gorge
#

i understand, yes

mild palm