'Fetch API Post request fails with "Request Failed SyntaxError: Unexpected end of JSON input"

Here is my GET request which works:

function getTodos() {
    fetch(window.location.href + 'api/todo')
        .then(response => response.json())
        .then(json => drawTodos(json))
        .catch(error => showToastMessage('Failed to retrieve todos...'));
}

But now I am trying to do a POST request but it fails

todo as shown in console.log

{
    "id": "ghCWaYWQTh",
    "title": "aaa",
    "description": "bbb",
    "done": false
}

function postTodo(todo) {
    let options = {
        method : 'POST',
            headers : {
                "Content-type": "application/json"
            },
             body : JSON.stringify(todo)
    };
    console.log(options);
    fetch(window.location.href + 'api/todo',options)
        .then(response => response.json())  // convert to json
        .then(json => console.log(json))    //print data to console
        .catch(err => console.log('Request Failed', err)); // Catch errors
    console.log(todo);
}

I cannot see a syntax error in my options variable?

-- the backend is in PHP --

I cannot see a syntax error in my options variable?

-- the backend is in PHP the get request works the post fails --

    $requestType = $_SERVER['REQUEST_METHOD'];
    $body = file_get_contents('php://input');
    $pathCount = count($path);
    require_once "dbconfig.php";
    switch ($requestType) {
        case 'GET':
            
            $query = "select * from todos";
            $result = mysqli_query($conn, $query);
            $todos = array();
            while($todo = mysqli_fetch_assoc($result)) {
                $todos[] = $todo;
            }
            echo json_encode($todos);

            break;
        case 'POST':
            $data = json_decode($body);
            $id = $data->id;
            $title = $data->title;
            $description = $data->description;
            $done = $data->done;

            $query = "INSERT INTO todos(id, title, description, done) 
                       VALUES ('" . $id . "', '" . $title . "',  '" . $description . "', " . $done . ")";
           // echo $query;

            if (mysqli_query($conn, $query) or die("Insert Query Failed")) {
                echo json_encode(array("message" => "Todo Inserted Successfully", "status" => true));
            } else {
                echo json_encode(array("message" => "Failed ToDo  Not Inserted ", "status" => false));
            }
            break;
        default:
            http_response_code(501);
            die();
            break;

This POST works with Postman, but not from Javascript



Solution 1:[1]

Your error is throwed from this

.then(response => response.json())  // convert to json

Because your response from BE API is 500 and the body of response can not be convert to Json

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 linhvp