【发布时间】: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