jeudi 4 juillet 2019

Enable cors at client side using reactjs

I have a web page developed using react it'a form which fetches some value at some remote server (currently it's localhost running on docker container).Now whenever i make a call for the url i keep getting this error

Access to fetch at 'http://localhost:8181/some_path' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.

so few methods i tries to enable CORS reading from web were

1. disable cores by using no-cors

  fetch(url, {
      method: "GET",
      mode: "no-cors",
      header: headers,
    })

it din't work as expected(i was always receiving empty value)

2. tried using a proxy server

fetch("http://cors-anywhere.herokuapp.com/" +url, {
  method: "GET",
  mode: "cors",
  header: headers,
})

it kept giving me this error

Not found because of proxy error: Error: connect ECONNREFUSED 127.0.0.1:8181

3. use a proxy in package.json

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:8181",

had no effect at all

4. add a chrome extension

but it's temporary and also does not function as expected.

i tried searching everywhere but none seemed to solve my problem.(by the way i can access the url directly from the browser) but were not helpful.

so is there a way to enable cors from my application(i.e client side) or any other way that could help me make a GET request.

PS: server cannot be changed :(

any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire