java Spring引导rest终结点返回null并带有获取请求
我已经在Java spring boot中创建了Rest端点。当我通过邮递员请求时,它会返回适当的响应。但当我使用react fetch时,如果return是Json,它不会在浏览器中显示任何响应
Spring启动控制器:
@RestController
@RequestMapping(path = "/v1/test")
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class TestController {
...
}
下面的端点正在返回适当的响应
@GetMapping(value = "/helloWorld", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public String getHelloWorld() {
return "Hello, World1!";
}
但当我尝试点击端点下方时,当我发出fetch
请求时,它返回null。但当我通过邮递员点击它时,它会返回适当的响应
@GetMapping(value = "/testEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public String returnTestResponse() {
HashMap<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("results", "value2");
return "{\"a\":1, \"b\":\"foo\"}";
}
还尝试返回POJO对象。但仍然没有回应
@GetMapping(value = "/testModel", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public SearchResultsModel testModel() {
this.myService.getSearchResult();
}
回应取回呼叫:
await fetch(ALL_ARTICLES_ENDPOINT, {
mode: 'no-cors',
method: 'GET',
redirect: 'follow',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
}).then(response => {
console.log(response);
})
.then(data => {
console.log('Success:', data);
}).catch((error) => {
console.error('Error:', error);
});
# 1 楼答案
邮递员有两个隐藏的邮件头,这些邮件头与所有请求一起发送。 检查
Hide auto-generated headers
react调用中缺少的是带有
application/json
值的Accept
头编辑:
刚才看到您将字符串作为json返回。您需要将其包装在POJO对象中,并在returnTestResponse类中返回
第二次编辑:
这会管用的。试着实现你的POJO
# 2 楼答案
问题是由于在获取请求中添加了
mode: 'no-cors'
选项引起的。这个选项帮助我摆脱了cors错误,但这意味着作为回报,我将无法在chrome中看到正文和标题为了解决这个问题,我删除了
mode: 'no-cors'
,并在我的spring boot控制器上添加了@CrossOrigin
注释