nginx
在location拦截目录下,处理options信令
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
add_header 'Access-Control-Allow-Headers' 'origin, content-type, accept, authorization,key,mobile,token,clienttype,version,Content-Type,if-none-match,x-3gpp-intended-identity';
add_header 'Content-Length' 0;
return 204;
}
}
服务端
拦截options请求,返回一系列Access-*
public abstract class PublicServlet extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(PublicServlet.class);
public void process(HttpServletContext ctx) throws Exception {
HttpServletRequest request = ctx.getRequest();
LOGGER.info("req url is {}", request.getRequestURL());
HttpServletResponse response = ctx.getResponse();
response.setHeader("Access-Control-Allow-Origin", "*");
String method = request.getMethod().toLowerCase();
switch (method) {
case "post":
doPost(request, response);
break;
case "get":
doGet(request, response);
break;
case "delete":
doDelete(request, response);
break;
case "put":
doPut(request, response);
break;
case "options":
doOptions(request, response);
break;
default:
break;
}
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doOptions(req, resp);
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", req.getHeader("access-control-request-headers"));
}
网友评论