3
votes

I don't seem to find any missed end input. This is the error that I recieve:

Uncaught (in promise) SyntaxError: Unexpected end of input at fetch.then.response (InventoryOnHand.js:33)

Below is my code: I have a value for the url.

 fetch(url + "GetItemMasterList", { 'mode': 'no-cors' })
   .then(response => response.json())
   .then(function (data) {
     console.log(data)
 });
1
It probably means the JSON you're getting from the server is invalid/incomplete.deceze♦
The data that comes back is probably not a valid JSON but an error of some kind, you should write an error handler and log it.Jeremy Thille
Your browser is blocking your frontend JavaScript code from having any access to the response at all. The reason is, that’s exactly what you’re asking the browser to do, by specifying 'mode': 'no-cors' . Among the effects of specifying that are, it tells the browser to treat the response as opaque —and it’s named that way because it means your JavaScript code can’t see it. At all. If the reason you’re specifying 'mode': 'no-cors' is that you otherwise get an error message about No Access-Control-Allow-Origin, then you need to realize that 'mode': 'no-cors' isn’t a fix for thatsideshowbarker

1 Answers

1
votes

This is a well known problem with CORS policy. To overcome this problem you need access rights to the server side API. In particular, you have to add a line in the header of php or another server endpoint:

<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');

// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);

// Use $jsonObj
print_r($jsonObj->message);

...
// End php
?>

Also, make sure NOT to have in the header of your server endpoint:

header("Access-Control-Allow-Credentials" : true);

Model of working fetch code with POST request is:

const data = {
        optPost: 'myAPI',
        message: 'We make a research of fetch'
    };
const endpoint = 'http://example.com/php/phpGetPost.php';

fetch(endpoint, {
    method: 'POST',
    body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
    console.info('fetch()', response);
    return response;
});