gpt4 book ai didi

java - 为什么 Spring boot 不接受我的 Axios POST 请求?

转载 作者:行者123 更新时间:2023-12-01 18:05:44 25 4
gpt4 key购买 nike

我正在尝试使用 Axios 将带有 JSON 正文的 POST 请求发送到 Spring boot 应用程序。但是,Spring boot 应用程序返回 Required request body ismissing:

当我使用 Postman 发送相同的请求时,它确实按预期工作。

我有一个非常简单的 Controller :

@RestController
@RequestMapping(value = "/deployments")
public class DeploymentController {
@PostMapping
public ResponseEntity<Deployment> createDeployment(@RequestBody Deployment deployment) {
//DoStuff
}
}

我发布的正文在两种情况下都是相同的:

{
"name": "testdeployment2",
"domainName": "domain.local",
"repository": "KB",
"branch": "master",
"servicepack": "6.5.1"
}

当我使用 Postman 发送请求时,请求如下所示:

{
"args": {},
"data": "{\"name\":\"testdeployment2\",\"domainName\":\"domain.local\",\"repository\":\"KB\",\"branch\":\"master\",\"servicepack\":\"6.5.1\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Cache-Control": "no-cache",
"Content-Length": "129",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Postman-Token": "238d83b0-1f14-4828-abf5-45978a80c008",
"User-Agent": "PostmanRuntime/7.22.0",
"X-Amzn-Trace-Id": "Root=1-5e6221c7-9be7dcc1163e105cd3495bf8"
},
"json": {
"branch": "master",
"domainName": "domain.local",
"name": "testdeployment2",
"repository": "KB",
"servicepack": "6.5.1"
},
"origin": "IP",
"url": "http://httpbin.org/post"
}

axios代码:

const url = 'http://httpbin.org/post';
const options = {
headers: {
'Content-Type' : 'application/json'
}
};

this.$http.post(
url,
this.form,
options
).then(result => {
this.result = result;
}).catch(error => {
alert(error);
});

Axios 请求如下所示:

{
"args": {},
"data": "{\"name\":\"testdeployment2\",\"domainName\":\"domain.local\",\"repository\":\"KB\",\"branch\":\"master\",\"servicepack\":\"6.5.1\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9,nl;q=0.8",
"Content-Length": "129",
"Content-Type": "application/json",
"Dnt": "1",
"Host": "httpbin.org",
"Origin": "http://localhost:8080",
"Referer": "http://localhost:8080/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-5e6223c7-35d5028ab672229267f65e9c"
},
"json": {
"branch": "master",
"domainName": "domain.local",
"name": "testdeployment2",
"repository": "KB",
"servicepack": "6.5.1"
},
"origin": "IP",
"url": "http://httpbin.org/post"
}

有什么我在这里没有看到的吗?为什么Postman可以工作,而Axios却不能?

最佳答案

所以我完全忘记检查 API 端的 CORS。在我的 Controller 方法上允许所有 CORS 后,它现在可以工作了。哦!

关于java - 为什么 Spring boot 不接受我的 Axios POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60562148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com