执行放置请求时,req.body为空对象

时间:2020-06-16 13:21:23

标签: javascript reactjs firebase express put

我正在执行从前端到后端的PUT请求,后端功能将更新我的Firestore数据库。该函数本身可以正常工作(可以通过邮递员等调用),但不能从前端调用,因为req.body始终是一个空对象。我当然检查了许多其他类似的情况,添加了一堆标题和其他内容,但是没有一个解决我的问题。这是我的后端代码:

router.put('/:id/results', async (req, res) => {
    try {
        console.log("Updating results...") //THIS IS LOGGED
        console.log(req.body)              // THIS LOGS {}
        let hamsters = []
        console.log(req.params.id)          //LOGS ID
        let snapShots = await db.collection('hamsters').where("id", "==", parseInt(req.params.id)).get()
        snapShots.forEach(doc => {
            hamsters.push(doc.data())
        })
        if (req.body.wins == 1) {
            hamsters[0].wins++
            res.send(`${hamsters[0].name} now has ${hamsters[0].wins} wins!`)
        } else if (req.body.defeats == 1) {
            hamsters[0].defeats++
            res.send(`${hamsters[0].name} now has ${hamsters[0].defeats} defeats!`)
        } else {
            throw ("You must either increase wins or defeats by 1") //THIS IS LOGGED
        }
        hamsters[0].games++
        db.collection('hamsters').doc(req.params.id).set(hamsters[0])
    }
    catch (err) {
        console.error(err)
    }
})

我的前端函数根据结果参数有两种不同的方法,现在它们看起来略有不同,只是说明我写请求的方式似乎无关紧要。该函数目前不返回任何内容,因为它只需要更新数据库。

export async function putBattleStats(hamsterID, outcome) {
    try {
        if (outcome === "win") {
            const response = await fetch(`/hamsters/${hamsterID}/results`,
                {
                    method: 'PUT', headers: { "Content-Type": "application/json/x-www-form-urlencoded" }, body: {
                        "hamsterID": JSON.stringify(hamsterID),
                        "wins": +1
                    }
                })
        } else if (outcome === "defeat") {
            const response = await fetch(`/hamsters/${hamsterID}/results`,
                {
                    method: 'PUT', body: {
                        "hamsterID": hamsterID,
                        "defeats": +1
                    }
                })
        }
    }
    catch (e) {
        console.error('Fetch failed because', e)
        return null
    }
}

就像我说的那样,我已经尝试过各种头文件,已经安装了node-fetch,并且还将这些行放在了server.js文件中:

const bodyParser = require('body-parser')
    server.use(bodyParser.urlencoded({ extended: true }));
    server.use(bodyParser.json())

    server.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

我只是希望我缺少明显的东西。

1 个答案:

答案 0 :(得分:0)

可能是因为您没有对整个身体进行细化处理。

尝试一下:

const response = await fetch(`/hamsters/${hamsterID}/results`,
// change this URL
    {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        // this can just be 'application/json' in your case
        body: JSON.stringify({
            hamsterID: hamsterID,
            wins: 1
        })
    })