Spring 后端处理options请求,解决跨域问题

当一个请求跨域时,会先发一个options请求,成功后再发原请求

@ResponseBody
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addWatcher(){
	xxx
	...
	setCORS(resp,request);
    return response.toString();
}

@ResponseBody
@RequestMapping(value = {"/add"}, method = RequestMethod.OPTIONS)
public String options(HttpServletResponse resp,HttpServletRequest request){
    setCORS(resp,request);
    return "success";
}

private void setCORS(HttpServletResponse resp,HttpServletRequest request){
    resp.setStatus(200);
    resp.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    resp.setHeader("Access-Control-Allow-Headers", "content-type");
    resp.setHeader("Access-Control-Allow-Credentials","true");
}

如果所有接口都需要跨域配置,也可以直接用filter统一解决:
Spring Filter处理跨域

你可能感兴趣的:(Spring,spring,java,servlet)