Body 的提取在 Next.js API 端点调用中返回空 object

Body of fetch returning empty object in Next.js API endpoint call

我在 Next.js 中进行 API 调用时遇到问题,该调用正在删除数据库中的项目。我正在使用提取的“body”字段将字符串发送到 API。获取调用是在 Next.JS 页面中进行的,API 端点位于 Next.js 生成的 API 文件夹中。当我从请求中尝试 console.log body 时,它 return 是一个空的 object。下面是页面代码,然后是 API 端点的代码。还将提供 API 端点的 console.log 的屏幕截图。

   const handleRemoveItem = useCallback(async(event) => {
        event.preventDefault()
        
        var itemSKU = event.target.value;

        const response = await fetch('/api/SB-RemoveProduct', {
            method:'POST',
            body: itemSKU
            }).then((r) => {
              return r
            }).catch((err) => {
              throw(err)
            });
        var deleteConfirm = await response.json();

        console.log(deleteConfirm);
    },[])

API端点

export default withSession(async (req, res) => {
    var itemSKU = req.body

    console.log("You are here 1");
    console.log(itemSKU);

    switch (req.method) {
        case 'POST': {
            var productRemoved = await removeProduct(itemSKU, req, res)
            return productRemoved;
            break
        }
        case 'GET': {
            console.log('try writting a route')
            break
        }
        case 'DELETE': {
            console.log('try writting a route')
            break
        }
        case 'UPDATE': {
            console.log('try writting a route')
            break
        }
    }

});

export const removeProduct = async (itemSKU, req, res) => {

    var params = {
        TableName: "products",
        Key: itemSKU
    }
    console.log("You are here 2");
    console.log(itemSKU); // this console.log and the one above both return {}
    DB.delete(params, function(err, data) {
        if (err) {
            console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2));
            res.status(200).send(data)
        }
    });
    
}

编辑 1:

收到一些反馈后,我添加了 headers 和 'Content-Type':'text/plain'、'Accept':'text/plain',结果相同。我还验证了我传递给 body 的变量是一个字符串。下面将是更新代码的页面。

    const handleRemoveItem = useCallback(async(event) => {
        event.preventDefault()
        
        var itemSKU = event.target.value;
        console.log(typeof(itemSKU));

        const response = await fetch('/api/SB-RemoveProduct', {
            method:'POST',
            body: itemSKU,
            mode: "cors",
            headers: {
                'Accept': 'text/plain',
                'Content-Type': 'text/plain'
              },
            }).then((r) => {
              return r
            }).catch((err) => {
              throw(err)
            });
        var deleteConfirm = await response.json();

        console.log(deleteConfirm);
    },[])

编辑 2:

根据以下解决方案的建议,我能够 return itemSKU 的值与之前不同。这一次,项目不是空的,而是 returned 为未定义。我所做的更改如下:

页数:

const handleRemoveItem = useCallback(async(event) => {
        event.preventDefault()
        
        var itemSKU = event.target.value;
        console.log(typeof(itemSKU));

        const response = await fetch('/api/SB-RemoveProduct', {
            method:'POST',
            body: JSON.stringify({itemSKU}),
            }).then((r) => {
              return r
            }).catch((err) => {
              throw(err)
            });
        var deleteConfirm = await response.json();

        console.log(deleteConfirm);
    },[])

API端点:

export default withSession(async (req, res) => {
    var itemSKU = req.body.itemSKU //req.body.itemSKU is returning undefined.

    console.log("You are here 1");
    console.log(itemSKU);

    switch (req.method) {
        case 'POST': {
            var productRemoved = await removeProduct(itemSKU, req, res)
            return productRemoved;
            break
        }
        case 'GET': {
            console.log('try writting a route')
            break
        }
        case 'DELETE': {
            console.log('try writting a route')
            break
        }
        case 'UPDATE': {
            console.log('try writting a route')
            break
        }
    }

});

export const removeProduct = async (itemSKU, req, res) => {

    var params = {
        TableName: "products",
        Key: itemSKU
    }
    console.log("You are here 2");
    console.log(itemSKU);
    // DB.delete(params, function(err, data) {
    //     if (err) {
    //         console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
    //     } else {
    //         console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2));
    //         res.status(200).send(data)
    //     }
    // });
    
}

删除headers,包括Content-type: plain/text,然后...

在您的请求中,更改

body: itemSKU,

body: JSON.stringify({ itemSKU });

在你的API中,你可以

console.log('req.body.itemSKU', req.body.itemSKU)

最终...

//client side
fetch('/api/...', { method: 'POST', body: JSON.stringify({...}))
.then(res => res.json())
.then(data => console.log('data', data)); 
//prints { value1: 'abc', value2: 'efg'}

然后API那边

export default async(req, res) => {

       console.log('req.body.itemSKU', req.body.itemSKU);

       res.json({ value1: 'abc', value2: 'efg'})
}