最初的代码时在特定方法里写响应头的,代码经过不断演化,变成以下

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));
}

 

posted on 2020-02-28 16:06  你不知道的浪漫  阅读(513)  评论(0编辑  收藏  举报