You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13.2中Axios POST报Unexpected end of JSON input错误,Fetch正常

问题:Next.js 13.2中Axios POST请求报错,Fetch却正常

在Next.js 13.2里调用API的POST方法时,逻辑一致的两个函数,Axios抛出Unexpected end of JSON input错误,但Fetch能正常请求,且API未做任何修改。奇怪的是Axios的GET请求完全正常,用Axios时还出现过readablestream { locked: false, state: 'readable', supportsbyob: false }的信息。试过把后端的.json()改成.text()等方法,还是没解决,求相关见解。


前端代码

Axios实现

function handleSubmit(event) {
    event.preventDefault();

    var newBlog = {
        title: title,
        content: content,
    }

    axios.post('/api/blogs', JSON.stringify(newBlog))
    .then(response => {
        console.log(response.data);
    }).catch(error => {
        console.log(error);
    });
       
    // 另一种POST调用尝试
    // axios({
    //     url: '/api/blogs',
    //     method: "POST",
    //     headers: {
    //         "content-type": "application/json",
    //     },
    //     body: JSON.stringify({
    //         title: title,
    //         content: content,
    //     }),
    // }).then(response => {
    //     console.log(response.data);
    // }).catch(error => {
    //     console.log(error.data);
    // });
}

Fetch实现

async function handleSubmit2() {
    const postData = {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify({
            title: title,
            content: content,
        }),
    };
    const res = await fetch(`/api/blogs`, postData);
    const response = await res
    if (response.response.message !== "success") return;
}

后端代码

export async function POST(req, res) {
    try {
        // Axios请求时,这里会抛出"SyntaxError: Unexpected end of JSON input"
        const { title, content } = await req.json()

        const result = await executeQuery({ query: "INSERT INTO blogs (title, content, date) VALUES (?, ?, ?)", values: [title, content, new Date()] });

        const formattedResults = JSON.stringify(result);
        console.log(formattedResults)
        return formattedResults;
    } catch (error) {
        console.error("Error on create blog:", error);
        return false // res.status(500).send(formattedResults);
    }
}

db.jsx(executeQuery所在文件)

import mysql from 'serverless-mysql';

const db = mysql({
    config: {
        host: process.env.DBHOST,
        port: process.env.DBPORT,
        database: process.env.DB,
        user: process.env.DBUSER,
        password: process.env.DBPASS
    }
});
export default async function executeQuery({ query, values }) {
    try {
        const results = await db.query(query, values);
        await db.end();
        return results;
    } catch (error) {
        return { error };
    }
}

问题原因及解决办法

1. Axios请求参数格式错误

Axios的post方法第二个参数如果是对象,会自动序列化为JSON并设置Content-Type: application/json,但你手动调用了JSON.stringify(newBlog),导致发送的是字符串形式的JSON,后端req.json()解析时直接失败。

修改Axios调用:

// 去掉JSON.stringify,直接传对象
axios.post('/api/blogs', newBlog)
.then(response => {
    console.log(response.data);
}).catch(error => {
    console.log(error);
});

如果用配置式调用,注意Axios用的是data参数而非Fetch的body,之前注释里的代码参数名写错了:

axios({
    url: '/api/blogs',
    method: "POST",
    headers: {
        "content-type": "application/json",
    },
    // 替换body为data,直接传对象即可
    data: {
        title: title,
        content: content,
    },
}).then(response => {
    console.log(response.data);
}).catch(error => {
    console.log(error);
});

2. 后端API返回格式不符合Next.js要求

Next.js 13+的App Router API路由要求返回NextResponse对象,你直接返回字符串或false会导致响应格式异常,Axios对响应格式的容错性比Fetch低,因此解析报错。

修改后端POST函数:

import { NextResponse } from 'next/server'; // 引入NextResponse

export async function POST(req, res) {
    try {
        const { title, content } = await req.json()

        const result = await executeQuery({ query: "INSERT INTO blogs (title, content, date) VALUES (?, ?, ?)", values: [title, content, new Date()] });

        // 返回标准JSON响应
        return NextResponse.json(result, { status: 200 });
    } catch (error) {
        console.error("Error on create blog:", error);
        // 错误时返回标准错误响应
        return NextResponse.json({ error: 'Failed to create blog' }, { status: 500 });
    }
}

3. Fetch代码的小问题(顺带修复)

原Fetch代码里没解析响应内容,且判断逻辑有误,调整如下:

async function handleSubmit2() {
    const postData = {
        method: "POST",
        headers: {
            "content-type": "application/json",
        },
        body: JSON.stringify({
            title: title,
            content: content,
        }),
    };
    const res = await fetch(`/api/blogs`, postData);
    const response = await res.json(); // 解析响应为JSON
    if (response.message !== "success") return; // 修正判断路径
}

内容的提问来源于stack exchange,提问作者omwASAP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:47:29