简体   繁体   English

获取 GET 请求的主体 (NodeJS + axios)

[英]Get body of GET request (NodeJS + axios)

Here's my request:这是我的要求:

        axios.get(BASE_URI + '/birds/random', {Stuff: "STUFF"})
        .then(randBird=>{
            const birdData = randBird.data
            const bird = {
                age: birdData.age,
                bio: birdData.profile.bio,
                displayname: birdData.profile.displayname,
                species: birdData.profile.species,
                _id: birdData._id
            }
            this.setState({currentBird:bird})
        })

Here's what happens on my router (on '/birds'):这是我的路由器上发生的事情(在“/birds”上):

birdRouter.route('/random').get((req, res)=>{
    console.log('req.body = ', req.body)
    User.count().exec((err, num)=>{
        if(err){
            console.log(err)
            return res.send({error: err})
        }
        const random = Math.floor(Math.random() * num)
        User.findOne().skip(random).exec((err, bird)=>{
            if(err){
                console.log(err)
                return res.send({error: err})
            }
            console.log(bird)
            res.send(bird)
        })

    })

Really, the only lines that are worth paying attention to in both snippets are the first and first two (for the first and second snippet, respectively).实际上,两个片段中唯一值得关注的行是前两行(分别针对第一个和第二个片段)。

The request goes through, but my console.log shows this:请求通过,但我的 console.log 显示:

req.body = {}

What did I do wrong here?我在这里做错了什么?

Some browsers and libraries don't support HTTP get method with a body.一些浏览器和库不支持带有主体的 HTTP get 方法。 You can switch to POST/PUT and see if it works as expected.您可以切换到 POST/PUT 并查看它是否按预期工作。

Usually in GET method we are not passing body data.通常在 GET 方法中,我们不传递正文数据。 instead of body data you can pass in query string.您可以在查询字符串中传递而不是正文数据。 and also if you are using express server than you need to install a package body-parser to get data in body.并且如果您使用的是快速服务器,那么您需要安装一个包body-parser来获取正文中的数据。 please take a reference of issue posted in axios请参考axios 中发布的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM