最初的代码时在特定方法里写响应头的,代码经过不断演化,变成以下
response.setHeader("Access-Allow-Control-Origin","*"); response.setHeader("Access-Control-Allow-Headers","*"); response.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, OPTIONS");
java代码:
@PostMapping("query")
@ResponseBody
public JsonResult query(String mapId,HttpServletResponse response)
{
response.setHeader("Access-Allow-Control-Origin","*");
response.setHeader("Access-Control-Allow-Headers","*");
response.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, OPTIONS");
if(Objects.isNull(mapId))
{
return errorResult("地图模型载入失败");
}
List<SnapShot> list = handleInternal(mapId);
if(Objects.isNull(list))
{
return errorResult("地图模型载入失败");
}
String lastUpdateTime = statusService.queryStatus("lastUpdateTime");
return successResult("成功", ImmutableMap.of("updateTime",lastUpdateTime,"result",list));
}
可是还会报错
Access to XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
和同事咨询了一下,解决方法如下
在对应的方法加注解
@CrossOrigin(origins = "*", maxAge = 3600) @PostMapping("query") @ResponseBody public JsonResult query(String mapId) { if(Objects.isNull(mapId)) { return errorResult("地图模型载入失败"); } List<SnapShot> list = handleInternal(mapId); if(Objects.isNull(list)) { return errorResult("地图模型载入失败"); } String lastUpdateTime = statusService.queryStatus("lastUpdateTime"); return successResult("成功", ImmutableMap.of("updateTime",lastUpdateTime,"result",list)); }
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。