axios get函数发送空请求
Axios get function sends empty request
我正在做一个简单的 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
}
})
和get结束点
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)
})
授权正确,console.log在“auth”函数中正确显示和验证令牌。不幸的是,端点在控制台中显示 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)
})
GET 请求没有数据或正文。检查这个答案
TLDR
axios({
method: 'GET',
url: `http://localhost:4444/next/api`,
params: {
id: 'id'
}
})
我正在做一个简单的 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
}
})
和get结束点
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)
})
授权正确,console.log在“auth”函数中正确显示和验证令牌。不幸的是,端点在控制台中显示 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)
})
GET 请求没有数据或正文。检查这个答案
TLDR
axios({
method: 'GET',
url: `http://localhost:4444/next/api`,
params: {
id: 'id'
}
})