Today you encounter a cross-domain problem record under learning:
First, the question:
Browser Console error when a custom header field is included in a cross-domain request.
Request header field Xfilesize is not allowed by access-control-allow-headers
Second, Reason:
Cross-domain requests that contain custom header fields, the browser sends an options request to the server to detect whether the server allows custom cross-domain fields.
If allowed, the actual post/get normal request continues, otherwise the error shown in the header is returned.
Options Request:
Request Url:http://xxx.yyy.com/zzz/api/file/uploadfile2.do request Method:options Status code:200 OK Remote address:47.92.87.25:80 Referrer policy:no-referrer-when-downgrade
Request Headers:
accept:*/* accept-encoding:gzip, deflate accept-language:zh-cn,zh;q=0.9,en;q=0.8 Access-control-request-headers:content-type,xfilecategory,xfilename,xfilesize Access-control-request-method:post connection:keep-alive Host:service.bz12306.com origin:null user-agent:mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) applewebkit/537.36 (khtml, like Gecko) chrome/63.0.3239.132 safari/537.36
The 4th behavior asks the server if a cross-domain custom header field is supported, and the server needs an appropriate response.
Access-control-request-headers:content-type,xfilecategory,xfilename,xfilesize
Third, the solution:
The server needs to answer the options request, the answer header contains Access-control-allow-headers, and the value contains the value Access-control-request-headers in the options request.
The following is the options request processing code set in the Java server-side filter.
@Override Public voidDoFilter (servletrequest req, Servletresponse resp, filterchain chain)throwsIOException, servletexception {Try{httpservletrequest Hreq=(httpservletrequest) req; HttpServletResponse Hresp=(HttpServletResponse) resp; //cross-DomainHresp.setheader ("Access-control-allow-origin", "*"); //cross-domain HeaderHresp.setheader ("Access-control-allow-methods", "*"); Hresp.setheader ("Access-control-allow-headers", "Content-type,xfilename,xfilecategory,xfilesize"); //The browser will first make an options request and continue to send a formal POST request if the request passes//Request to configure options returns if(Hreq.getmethod (). Equals ("OPTIONS") {hresp.setstatus (HTTPSTATUS.SC_OK); //hresp.setcontentlength (0); hresp.getwriter (). Write ("OPTIONS returns OK"); return; } //The Filter is only chained, and the request is still forwarded to the destination address. Chain.dofilter (req, resp); } Catch(Exception e) {e.printstacktrace (); } }
Here, this is the answer header for the desired setting:
Hresp.setheader ("Access-control-allow-headers", "content-type,xfilename,xfilecategory,xfilesize");
* The case of the value in the header looks insensitive.
Reprinted: 79076704
Request header field Content-type is not allowed by access-control-allow-headers