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)) 
6
  • can you show the full code? Commented Jul 6, 2017 at 22:24
  • you can remove the comma on line 49 Commented Jul 6, 2017 at 22:26
  • @Chris removing comma on line 49 not work Commented Jul 6, 2017 at 22:35
  • Your API endpoint is returning something other than valid JSON. Commented Jul 6, 2017 at 22:39
  • when the fetch response is successful, are you setting the result state to the given response? Commented Jul 6, 2017 at 22:53

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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 '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
Yes, exactly. Set the Access-Control-Allow-Origin header on your server's routes. You don't want to use no-cors here. It's a backend issue, not one on the frontend.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.