权限没有,则隐藏 function forum_list_access_filter($forumlist, $gid, $allow = 'allowread') { global $grouplist; if (empty($forumlist)) return array(); if (1 == $gid) return $forumlist; $forumlist_filter = $forumlist; $group = $grouplist[$gid]; foreach ($forumlist_filter as $fid => $forum) { if (empty($forum['accesson']) && empty($group[$allow]) || !empty($forum['accesson']) && empty($forum['accesslist'][$gid][$allow])) { unset($forumlist_filter[$fid]); } unset($forumlist_filter[$fid]['accesslist']); } return $forumlist_filter; } function forum_filter_moduid($moduids) { $moduids = trim($moduids); if (empty($moduids)) return ''; $arr = explode(',', $moduids); $r = array(); foreach ($arr as $_uid) { $_uid = intval($_uid); $_user = user_read($_uid); if (empty($_user)) continue; if ($_user['gid'] > 4) continue; $r[] = $_uid; } return implode(',', $r); } function forum_safe_info($forum) { //unset($forum['moduids']); return $forum; } function forum_filter($forumlist) { foreach ($forumlist as &$val) { unset($val['brief'], $val['announcement'], $val['seo_title'], $val['seo_keywords'], $val['create_date_fmt'], $val['icon_url'], $val['modlist']); } return $forumlist; } function forum_format_url($forum) { global $conf; if (0 == $forum['category']) { // 列表URL $url = url('list-' . $forum['fid'], '', FALSE); } elseif (1 == $forum['category']) { // 频道 $url = url('category-' . $forum['fid'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = url('read-' . trim($forum['brief']), '', FALSE); } if ($conf['url_rewrite_on'] > 1 && $forum['well_alias']) { if (0 == $forum['category'] || 1 == $forum['category']) { $url = url($forum['well_alias'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = ($forum['threads'] && $forum['brief']) ? url($forum['well_alias'] . '-' . trim($forum['brief']), '', FALSE) : url($forum['well_alias'], '', FALSE); } } return $url; } function well_forum_alias() { $forumlist = forum_list_cache(); if (empty($forumlist)) return ''; $key = 'forum-alias'; static $cache = array(); if (isset($cache[$key])) return $cache[$key]; $cache[$key] = array(); foreach ($forumlist as $val) { if ($val['well_alias']) $cache[$key][$val['fid']] = $val['well_alias']; } return array_flip($cache[$key]); } function well_forum_alias_cache() { global $conf; $key = 'forum-alias-cache'; static $cache = array(); // 用静态变量只能在当前 request 生命周期缓存,跨进程需要再加一层缓存:redis/memcached/xcache/apc if (isset($cache[$key])) return $cache[$key]; if ('mysql' == $conf['cache']['type']) { $arr = well_forum_alias(); } else { $arr = cache_get($key); if (NULL === $arr) { $arr = well_forum_alias(); !empty($arr) AND cache_set($key, $arr); } } $cache[$key] = empty($arr) ? '' : $arr; return $cache[$key]; } ?>javascript - Body of fetch returning empty object in Next.js API endpoint call - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Body of fetch returning empty object in Next.js API endpoint call - Stack Overflow

programmeradmin9浏览0评论

I am having trouble with making an API call in Next.js that is deleting an item in a database. I am using the "body" field of the fetch to send a string to the API. The fetch call is being made in a Next.JS page and the API endpoint is in the API folder generated by Next.js. When I attempt the console.log the body from the request it is returning an empty object. Below will be the code for the page and then the code for the API endpoint. A screenshot of the console.log from the API endpoint will also be given.

Page

   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 endpoint

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

EDIT 1:

After receiving some feedback, I added headers with the 'Content-Type': 'text/plain', 'Accept': 'text/plain' and ended with the same result. I also verified that the variable that I am passing into the body is a string. Below will be page for the code updated.

    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);
    },[])

I am having trouble with making an API call in Next.js that is deleting an item in a database. I am using the "body" field of the fetch to send a string to the API. The fetch call is being made in a Next.JS page and the API endpoint is in the API folder generated by Next.js. When I attempt the console.log the body from the request it is returning an empty object. Below will be the code for the page and then the code for the API endpoint. A screenshot of the console.log from the API endpoint will also be given.

Page

   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 endpoint

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

EDIT 1:

After receiving some feedback, I added headers with the 'Content-Type': 'text/plain', 'Accept': 'text/plain' and ended with the same result. I also verified that the variable that I am passing into the body is a string. Below will be page for the code updated.

    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);
    },[])

EDIT 2:

Following the suggestions from a solution below, I was able to return a different value for itemSKU than what I had before. This time, instead of the item being empty, it returned as undefined. The changes I made are below:

page:

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 Endpoint:

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)
    //     }
    // });
    
}

Share Improve this question edited Feb 15, 2022 at 15:01 Shafi Kamal asked Feb 15, 2022 at 4:42 Shafi KamalShafi Kamal 1111 gold badge3 silver badges10 bronze badges 8
  • 1 You're sending a text/plain request body. Is that what you're wanting to send? Is the API configured to handle such a request content-type? – Phil Commented Feb 15, 2022 at 4:47
  • So normally I would use JSON.stringify() when passing information to the request body, but doing so returns the exact same result. – Shafi Kamal Commented Feb 15, 2022 at 5:17
  • You would also need to set the appropriate content-type header – Phil Commented Feb 15, 2022 at 5:19
  • Sorry, I am still a pretty novice dev, do you mind explaining the content-type header and what I would need to change it to? – Shafi Kamal Commented Feb 15, 2022 at 5:57
  • See this answer – Phil Commented Feb 15, 2022 at 6:00
 |  Show 3 more ments

2 Answers 2

Reset to default 4

remove the headers, including Content-type: plain/text, then...

In your request, change

body: itemSKU,

to

body: JSON.stringify({ itemSKU });

In your API, you can

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

Eventually...

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

Then on API side

export default async(req, res) => {

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

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

I have faced this same issue if someone is facing the same in 2024. Here is what worked for me:

You have to convert the request to json

export async function POST(request) {
  const formData = await request.json();
  console.log(formData);
  // save to the database or...
  return NextResponse.json({
    message: "Form data submitted successfully!",
    data: data,
  });
}

Credit to this User on GitHub

发布评论

评论列表(0)

  1. 暂无评论