13

When using the Fetch API to fetch some JSON from a REST API on my local server and trying to parse the response with response.json(), I am receiving an unexpected end of input error.

The error is easily reproducible on my local server with the following one-liner:

fetch(new Request('http://localhost:9950/RestService/v2/search/find/1', {mode: 'no-cors'})).then(function(response) { response.json(); });

// Output from Chrome console:
// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
// VM424:1 Uncaught (in promise) SyntaxError: Unexpected end of input
//     at SyntaxError (native)
//     at <anonymous>:1:128

If I view the Network tab, I can see that my request was fulfilled by the server, and if I preview the response I can see that there is valid JSON available there (I double-checked this by copying and pasting the JSON from the Network Response tab in to jsonlint.com). Here is a sample of the response I am getting from the server:

{
    "SearchMatches": [{
        "Extracts": ["<b>1<\/b>.txt...", "<b>1<\/b>"],
        "Title": "1.txt",
        "Url": "C:\\TestShare4\\500Docs\\1.txt"
    }]
}

If I try to use response.text() instead of response.json() I get an empty string.

Any thoughts on where I could be going wrong with this?

Note that I have a requirement to not depend on any other frameworks or libraries other than what is natively supported by the browser.

Aaron Cunnington
  • 1,631
  • 2
  • 15
  • 23
  • I'm having a similar issue, did you solve this? – Lars Nyström May 16 '16 at 12:33
  • 2
    I had the same issue and it was solved by http://stackoverflow.com/a/35291777/3192470. – Evgenia Karunus Oct 22 '16 at 01:43
  • 1. Try removing the `no-cors` option and check if this is the issue. 2. If not, what server are you using? I'm curious about the response headers the server sends. Make sure `Content-Type: "application/json"` header is returned by the server – Raul Rene May 25 '18 at 13:25

0 Answers0