簡體   English   中英

獲取 API Post 請求失敗,顯示“請求失敗語法錯誤:JSON 輸入意外結束”

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

這是我的 GET 請求,它有效:

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

但是現在我正在嘗試執行 POST 請求但它失敗了

todo 如 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);
}

我在選項變量中看不到語法錯誤?

-- 后端在 PHP --

我在選項變量中看不到語法錯誤?

-- 后端在 PHP get 請求有效 post 失敗 --

    $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;

此 POST 適用於 Postman,但不適用於 Javascript

您的錯誤由此引發

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

因為您來自 BE API 的響應是 500 並且響應主體無法轉換為 Json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM