Fetch() Unexpected End of Input

fetch() unexpected end of input

Opaque Responses

A response for a no-cors request to a cross-origin resource has a response type of 'opaque'. If you log the response before trying to turn it to JSON, you will see a type of "opaque".

Opaque types are listed as "severely restricted" as explained in the fetch spec on whatwg.org.

An opaque filtered response is a filtered response whose type is "opaque", url list is the empty list, status is 0, status message is the empty byte sequence, header list is empty, body is null, and trailer is empty.

They cannot currently be read when the type is opaque as explained on Google's docs on the opaque type.

An opaque response is for a request made for a resource on a different origin that doesn't return CORS headers. With an opaque response, we won't be able to read the data returned or view the status of the request, meaning we can't check if the request was successful or not. With the current fetch() implementation, it's not possible to make requests for resources of a different origin from the window global scope.

Enable CORS support on your server

This can be environment-dependent or language-dependent. For example, you can change CORS settings within Nginx's environment by changing your server config, or you can specify headers within your application code such as in PHP.

I highly recommend reading the Mozilla documentation on CORS requests and also Access-Control-Allow-Origin.

An example in PHP:

<?php
header("Access-Control-Allow-Origin: *"); // "*" could also be a site such as http://www.example.com

SyntaxError: Unexpected end of input in fetch API

You are trying to parse text into json.
You can use res.json() instead of res.send() from your backend.

using of fetch API the unexpected end of input error occurr

You said mode:'no-cors', so fetch doesn't attempt to read data across origins (which is forbidden by default), and it doesn't throw an error (because you told it you didn't want to try to read data across origins).

Change it to mode: "cors".

Ensure the server you are requesting the data from grants you permission to read the response using the Access-Control-Allow-Origin header.


See also this answer about the Same Origin Policy.

fetch() POST requests with Express: unexpected end of JSON input

This error means that you're trying to parse something that is not a valid JSON object.

"SyntaxError: Unexpected end of JSON input at postText (script.js:23)"

Which is true, because the response you're sending back to the frontend is not a JSON.

router.post("/result", (req, res) => {
console.log(req.body);
// The response is not a valid JSON object
res.send();
});

You can change res.send() to res.json() and give it a valid object.

res.json({ name:"John", age:30, car:null })


Related Topics



Leave a reply



Submit