提问人:Azima 提问时间:9/29/2018 最后编辑:mruanovaAzima 更新时间:2/27/2023 访问量:67534
Axios 请求中未发送正文数据
body data not sent in axios request
问:
我正在尝试通过axios请求将数据发送到我的后端脚本,但正文看起来是空的。
下面是从前端发送的请求:
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
}).then((res)=>{
console.log("api call sucessfull",res);
}).catch((err)=>{
console.log("api call unsucessfull",err);
this.props.toggleLoading(false);
})
下面是一个后端:
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.body);
})
但我的身体是空的。我得到的是标题和其他数据,但没有数据。{}
答:
27赞
pidizzle
9/29/2018
#1
GET 请求不应有正文。
将方法从“GET”更改为“POST”
这样:
axios.request({
method: 'POST',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
data: {
next_swastik: 'lets add something here'
},
})
并更改您的 API 以期待帖子
app.post('/next/api', verifyToken, function(req, res) {
console.log(req.body);
});
或
将属性更改为data
params
axios.request({
method: 'GET',
url: `http://localhost:4444/next/api`,
headers: {
'Authorization': token
},
params: {
next_swastik: 'lets add something here'
},
})
并更改 API 以注销参数
app.get('/next/api', verifyToken, function(req, res) {
console.log(req.params);
});
就像@MaieonBrix说的,确保你的标题包含你要发送的内容类型。
评论
23赞
user37309
10/27/2020
GET Bodies 不再从 HTTP 请求中被驱逐,建议将其更改为 POST 对我们这些使用我们无法控制的外部 API 的人没有帮助。
0赞
pidizzle
10/28/2020
我的答案不是针对人们点击他们无法控制的外部 api,而是针对您在上面看到的问题。我还说你“不应该”有一个 GET,而不是你“不能”
6赞
user37309
10/28/2020
也许吧,但现在这更多地取决于意见。由于标准现在不再明确排除GET机构,我想说“不应该”是一个非常个人的观点。当你搜索有关HTTP GET正文的答案时,这个答案也会出现在谷歌上,所以从这个意义上说,它是相当无用的。
3赞
Phil
3/15/2022
@user37309虽然它们可能不再被“放逐”,但它们在浏览器中根本不受支持。
10赞
MaieonBrix
9/29/2018
#2
看起来你只剩下两点来让它工作:
一:http方法应该设置为而不是,因为你要发送一些东西。
POST
GET
二:然后你可以添加HTTP头(就像你对授权头所做的那样):'application/json'
Content-Type
在后端,不要忘记使用某种身体解析器实用程序包,例如:body-parser,并使用您的应用程序进行设置。
我想您的服务器正在使用 express,以下是您将如何使用 express 进行操作:
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();
app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes
/* ... rest of your code */
-1赞
Pablo Papalardo
4/20/2019
#3
试试这个
this.axios('realties', { params: this.filter })
1赞
Abhishek
3/10/2021
#4
如果您收到“bodyParser 已弃用”的错误,请尝试以下操作 -
app.use(express.json()); //To parse JSON bodies (Applicable for Express 4.16+)
如果要从HTTP请求的正文中获取数据,请使用“post”方法。
评论
0赞
Sapthaka
2/8/2022
它既简单又有效!我没有收到“bodyparser deprecated”错误。但这对我有用。
0赞
josh hoffer
2/27/2023
#5
因为获取请求...一般没有身体。它们实际上是您在 url 栏中键入的内容。因此,您需要使用参数而不是正文。如果您希望单独使用它们,请使用查询字符串。
url/posts?post=post123&comment=comment321
在下面,对 url/posts/post123/comment321 => 发出的请求将填充以下两个参数。
您必须使用帖子,但不需要评论。
router.get("/posts/:post/:comment",async(req,res){
const postPermlink = req.params.post
const commentPermlink = req.params.comment ?? null
const postDbEntry = await Posts.findOne({permLink: postPermlink})
}
评论