0

I am using fetch to simply get data from a dummy api endpoint, but I get an unexpected end of input error when I add in the configs in the fetch function.

This works just fine and console logs an array of 200 items

componentDidMount() {
    let url = 'https://jsonplaceholder.typicode.com/todos';
    let config =  {
      method: "GET",
      mode: "no-cors",
      headers: {
        "access-control-allow-origin" : "*",
        "Content-type": "application/json; charset=UTF-8",
        "access-control-allow-headers": "content-type"
      }
    };


    fetch(url)
      .then(res => res.json())
      .then(data => this.setState({ data, }))

}

But when I add in the configs as a parameter, it shows and error.

componentDidMount() {
    let url = 'https://jsonplaceholder.typicode.com/todos';
    let config =  {
      method: "GET",
      mode: "no-cors",
      headers: {
        "access-control-allow-origin" : "*",
        "Content-type": "application/json; charset=UTF-8",
        "access-control-allow-headers": "content-type"
      }
    };


    fetch(url, config)   // This is where the error occurs
      .then(res => res.json())
      .then(data => this.setState({ data, }))

}

Error:

Dashboard.jsx:35 Uncaught (in promise) SyntaxError: Unexpected end of input
    at Dashboard.jsx:35

and

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://jsonplaceholder.typicode.com/todos with MIME type application/json.
  • 1
    Why are you sending `access-control-allow-origin` (CORS) headers from client side fetch API. These should be sent from server to avoid cross domain issues. Remove `access-control-allow-headers` and `access-control-allow-origin` headers. Here is working [code sandbox link](https://codesandbox.io/s/dazzling-meninsky-esw6c) – tarzen chugh Jun 03 '19 at 13:21

1 Answers1

0

first of all change mode: 'no-cors' to mode: 'cors'

about the CORS issue

You'll need to update the CORS headers on the server you are trying to request information from. These CORS policies are in place for security purposes

if you have access to it add this header :

'Access-Control-Allow-Origin: *'

or

'Access-Control-Allow-Origin: http://example.com'
Roy.B
  • 2,076
  • 14
  • 23
  • I am actually building an electron app, disabling cors on the browser doesnt help, and also I have included the above header that you have suggested but am still getting the CORS error! – Gagan Ganapathy Sudhir Ajjikut Jun 03 '19 at 13:11
  • 1
    @GaganGanapathySudhirAjjikut read carefully my answer, you will need to add headers to the server side if you have access to it – Roy.B Jun 03 '19 at 13:16