【问题标题】:Axios get function sends empty requestaxios get函数发送空请求
【发布时间】:2021-02-12 20:02:49
【问题描述】:

我正在做一个简单的 MERN 博客项目,尝试学习新事物。我已经制作了服务器,现在正在使用客户端。我已经用 Postman 测试了端点,它们工作正常。问题出在 axios 的客户端。

const sensorResponse = await axios({
        method: 'get',
        url: url,
        headers: {"X-Auth-Token": localStorage.getItem('auth-token'),
        "content-type": "application/json" },
        data : {
            userId: user.id
        }
    })

以及获取终点

router.get('/', auth, async (req,res)=>{
 const {userId} = req.body;
 console.log(req.body);
 console.log(userId);
 const blogs = await Blog.find({userId:userId})
 res.json(blogs)
 })

授权正确,“auth”函数中的console.log显示并正确验证了token。不幸的是,获取端点在控制台中将 req.body 显示为空对象。我尝试了另一个请求函数:

const blogResponse = await axios.get(url,data,headers)

但它的工作原理是一样的...... 你们能建议我这个请求应该是什么样子吗?

///// 编辑解决的问题

const sensorResponse = await axios({
        method: 'get',
        url: url,
        headers: {"x-auth-token": localStorage.getItem('auth-token'),
        "content-type": "application/json" },
        params: {
            'userId': user.id
        }
    })

要在请求中使用参数传递 userId,端点应如下所示:

router.get('/', auth, async (req,res)=>{
  const userId = req.query.userId;
   console.log(userId)
   const blogs= await Blog.find({userId:userId})
  res.json(blogs)

})

【问题讨论】:

    标签: node.js reactjs axios mern


    【解决方案1】:

    GET 请求没有数据或正文。检查这个答案here

    TLDR

    axios({
        method: 'GET',
        url: `http://localhost:4444/next/api`,
        params: {
           id: 'id'
        }
    })
    

    【讨论】:

    • 谢谢,我把它改成params,并尝试在服务器控制台中显示它,但仍然得到空对象。
    • 当您说服务器控制台时,您是指浏览器开发工具中的控制台选项卡吗?您是否仍然拥有上述控制台日志:const {userId} = req.body; console.log(req.body);,因为这不会记录。您应该能够查看网络选项卡并查看包含参数的标头,或者请求 URL 应显示为 http://somewhere.com?userId=USERID
    • 服务器控制台是指 VSCode 中的一个,服务器启动的地方。是的,我明白了。谢谢库尔蒂斯。我以前没想过只在控制台中显示整个 req 来查看我提供的参数在哪里。终于找到了,谢谢
    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 2019-02-12
    • 2020-06-25
    • 2020-02-05
    • 2019-09-13
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多