fetch API POST请求失败,“请求失败的语法:JSON输入的意外结束”

发布于 2025-01-23 14:32:03 字数 2539 浏览 4 评论 0原文

这是我的获取请求的工作:

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

但是现在我正在尝试执行邮政请求,但是

如Console中所示,

{
    "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请求作品帖子失败 -

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

该帖子与Postman合作,但不能来自JavaScript

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤凫 2025-01-30 14:32:03

您的错误是

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

因为您的API响应是500,并且响应的主体无法转换为JSON

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文