我有一个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 -X POST \
BACKEND_URL/settings \
-H 'Authorization: ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-d '[{"id":123,"settings":"SETTINGS"}]'
答案 0 :(得分:0)
可能您需要使用字符串格式(而不是数组格式)在主体部分中发送数据,是否可以尝试使用以下代码-
const data = [{"id":123,"settings":"SETTINGS"}];
....
axios.post(endpoint, JSON.stringify(data), { headers, params })
....