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
  • 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 Commented Jun 3, 2019 at 13:21

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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!
@GaganGanapathySudhirAjjikut read carefully my answer, you will need to add headers to the server side if you have access to it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.