5

When use fetch for request in server using headers return

SyntaxError: Unexpected end of input
    at index.js:50
    at <anonymous>

Line of code 50 is }).then(res => res.json())

What can be wrong?

This code fetch.

fetch(api-url, {
          mode: 'no-cors',
          method: "POST",
          headers: {
              'Accept': 'application/json',
                        'Content-Type': ' application/json',
                        'X-API-SERVER': '85499f9f'
                    },
        }).then(res => res.json())
          .then(res => {
            if (res.status === 200){
              console.log("accepted");
            }else {
              console.log(res.error);
            }

             console.log(res.error)
          }).catch(err => console.log(err))
user3058963
  • 105
  • 1
  • 2
  • 8

2 Answers2

3

Since you're requesting an API, you don't want to disable CORS. It's probably enough to just remove mode: 'no-cors' in your fetch request to fix this, as long as your API server sends the correct headers as well (Access-Control-Allow-Origin).

Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
  • when postman return ok but when fecth return this when remove no-cors. Fetch API cannot load https://-app-dobled.herokuapp.com/api/v1/create. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. index.js:60 TypeError: Failed to fetch – user3058963 Jul 06 '17 at 22:41
  • Yes, exactly. [Set the `Access-Control-Allow-Origin` header](https://stackoverflow.com/a/18311469/6941627) on your server's routes. You don't want to use `no-cors` here. It's a backend issue, not one on the frontend. – Fabian Schultz Jul 06 '17 at 22:45
0

With res.status you're trying to retrieve the status property from the response body (as returned by the json() function), not the response object itself.

xastor
  • 482
  • 5
  • 17