Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'
You need to remove the mode: 'no-cors'
setting from your request. Setting no-cors
mode is exactly the cause of the problem you’re having.
A no-cors
request makes the response type opaque
. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode explains:
no-cors
— JavaScript may not access any properties of the resultingResponse
So the effect of setting no-cors
mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”
People sometimes try setting no-cors
mode when a response doesn’t include the Access-Control-Allow-Origin
response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS
preflight.
But using no-cors
mode isn’t a solution to those problems. The solution is either to:
configure the server to which you’re making the request such that it sends the
Access-Control-Allow-Origin
response header, and such that it handlesOPTIONS
requestsor set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
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
Uncaught (in promise) SyntaxError: Unexpected end of input after json fetch
It's because the endpoint is not passing the right params in the response header.
Header should include:
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
I tested with Postman and the response had 8 headers: https://api.tibiadata.com/v2/characters/Burdeliusz.json
Connection →keep-alive
Content-Length →683
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:05:30 GMT
Server →nginx/1.10.3
Strict-Transport-Security →max-age=63072000; includeSubdomains; preload
X-Content-Type-Options →nosniff
X-Frame-Options →DENY
Example of Access Control Allow Origin: https://api.spacexdata.com/v2/launches
Access-Control-Allow-Origin →*
CF-RAY →447cd76c595fab66-YYZ
Connection →keep-alive
Content-Encoding →gzip
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:06:08 GMT
Expect-CT →max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server →cloudflare
Set-Cookie →__cfduid=d1dce3c5d11de37f960c7b47dc4f7d6701533845168; expires=Fri, 09-Aug-19 20:06:08 GMT; path=/; domain=.spacexdata.com; HttpOnly; Secure
Strict-Transport-Security →max-age=15552000; includeSubDomains
Transfer-Encoding →chunked
Vary →Accept-Encoding, Origin
X-Cache-Status →EXPIRED
X-Content-Type-Options →nosniff
X-DNS-Prefetch-Control →off
X-Download-Options →noopen
X-Frame-Options →SAMEORIGIN
X-Response-Time →151ms
X-XSS-Protection →1; mode=block
You can try asking the tibiadata people to add the headers
OR
Use a proxy to access the endpoint: http://jsfiddle.net/RouzbehHz/b95vcdhm/2/
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'https://api.tibiadata.com/v2/characters/Burdeliusz.json'
fetch(proxyUrl + targetUrl)
.then(blob => blob.json())
.then(data => {
console.table(data);
document.querySelector("pre").innerHTML = JSON.stringify(data, null, 2);
return data;
})
.catch(e => {
console.log(e);
return e;
});
You can recreate the proxy server:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
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) unless you try to parse the data as JSON.
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.
unexpected end of output in Fetching API in JavaScript
Try this:
let myinit={
method:'GET',
// mode:'no-cors',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive',
'Accept-Encoding' : 'gzip, deflate',
},
cache:'default'
};
let myRequest =new Request('https://cors-anywhere.herokuapp.com/https://opendata.ecdc.europa.eu/covid19/casedistribution/json/',myinit);
fetch(myRequest)
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data);
})
.catch(function (err) {
console.log('Fetch problem: ', err.message);
});
Related Topics
Performance Impact of Using CSS/JavaScript Source-Maps in Production
Dynamically Loading CSS File Using JavaScript with Callback Without Jquery
Iphone/iPad Triggering Unexpected Resize Events
CSS Transitions on New Elements
Jquery UI Autocomplete Positioning Wrong
What Is the Best Method to Reduce the Size of My JavaScript and CSS Files
How to Get Border Width in Jquery/Javascript
Reading Non-Inline CSS Style Info from JavaScript
Example of How to Load Static CSS Files from Node_Modules Using Webpack
Manipulating CSS with JavaScript
Viable Options for Running Nodejs on Android (Aug 2017)
Detect iOS Version Less Than 5 with JavaScript
Using Node.Js Require Vs. Es6 Import/Export
Change Background Image in Body
Indexof Method in an Object Array
Why Is My Asynchronous Function Returning Promise { ≪Pending≫ } Instead of a Value