POST请求随机发送,没有正文

问题描述 投票:0回答:1

我有一个Angular前端,它调用Java Spring Boot后端API。前端多次将以下请求发送到后端,但是其中一些失败,状态码为[[400。记录的错误为org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing。但是,当我查看Chrome中的Network标签时,请求看起来很不错,如果我再次发送它,它就成功了。但是最奇怪的是,如果我通过curl调用它,它永远不会失败。

前端:

const endpoint = 'BACKEND_URL/settings'; const data = [{"id":123,"settings":"SETTINGS"}]; const headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'ACCESS_TOKEN' }; const params = {}; axios.post(endpoint, data, { headers, params }) .then(function (response) { console.log(response.status, response.data); }) .catch(function (error) { console.log('error', error.response.status); });

后端:

@Api(tags = "API name", description = "API description") @RestController @RequestMapping("/") public class SettingsController { @ApiOperation("Endpoint name") @PostMapping(path = "/settings", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @Transactional public ResponseEntity<Boolean> updateSettings(@RequestBody @ApiParam("description") List<Settings> settings) throws ApiException { // unreachable code when there is no body } }

使用

curl拨打电话:

curl -X POST \ BACKEND_URL/settings \ -H 'Authorization: ACCESS_TOKEN' \ -H 'Content-Type: application/json' \ -d '[{"id":123,"settings":"SETTINGS"}]'
angular spring-boot axios http-post http-status-code-400
1个回答
0
投票
可能您需要使用字符串格式在主体部分发送数据,可以使用下面的代码尝试一下吗?

const data = [{"id":123,"settings":"SETTINGS"}]; .... axios.post(endpoint, JSON.stringify(data), { headers, params }) ....

© www.soinside.com 2019 - 2024. All rights reserved.