我有这个SimpleCORSFilter
:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "PATCH,POST,GET,OPTIONS,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
}
除此端点外,一切正常,在端点我创建自己的ResponseEntity
对象以返回页面内容:
@RequestMapping(value = ROOT + "/{businessId}/reviews", method = RequestMethod.GET)
public @ResponseBody HttpEntity<PagedResources<MenuReviewDto>> getAll(
@PathVariable(name = "businessId") Long businessId,
@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size,
Sort sort,
PagedResourcesAssembler assembler
) {
Pageable pageable = PageRequest.of(page, size, sort);
Page<ReviewDto> reviews = this.reviewService.getAll(businessId, pageable);
PagedResources<ReviewDto> pagedResources = assembler.toResource(reviews);
return new ResponseEntity<>(pagedResources, HttpStatus.OK);
}
这是当前失败的唯一请求,给了我典型错误:
Access to XMLHttpRequest at 'https://192.168.1.144:8443/r/api/v1/admin/businesses/3/reviews?page=0&sort=createdAt,desc&size=5' from origin 'https://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
奇怪的事情:
在此请求期间进行调试时,我看到doFilter()
中的SimpleCORSFilter
正在被调用。那么应该添加标题吗?!
答案 0 :(得分:0)
好的,这很快。我将其发布在这里,因为这让我有点惊讶。
我在日志输出中找到了这个
2019-08-1...ExceptionResolver : Resolved [org...Exception: Could not write JSON: ..
yadda,yadda,yadda ..
.. java.util.ArrayList[0]->mahlzeit.shared.review.ReviewRatingDto["isCut"])]
现在,让我们看看isCut
是什么:
public class ReviewRatingDto {
private Boolean isCut;
// ..
public void setIsCut(boolean isCut) {
this.isCut = isCut;
}
public boolean getIsCut() {
return isCut;
}
}
问题:是由吸气剂返回boolean
而不是Boolean
。当然,这是使用我选择的IDE来自动生成的代码,并且最终是我自己的错误,但是请注意,所产生的错误可能会导致您质疑CORS设置..