Fetch with Java Web configuration cors cross domain __web

Source: Internet
Author: User

Cross-domain: Requests that do not conform to the browser's homology policy cannot be executed, and the same source name, protocol, and Port are the same. Here the main introduction cors. cors Two kinds of requests: simple Request
Request method is head, GET, post any one of the request headers only the following fields
Accept accept-language content-language Last-event-id content-type (limited to application/x-www-form-urlencoded, multipart /form-data, Text/plain) not simple requests not-so-simple request
Not meeting simple request conditions is a simple request

Simple request

The browser makes a cors request by adding a Origin field to the header to indicate that the request was made by that source (protocol, domain name, port) for the server reference to choose whether to agree to the request. If the server allows, the following fields are added to the response header:

Access-control-allow-origin:

If the server allows access to a source, the field is the required field, and his value is generally the same as the Origin field in the request header, which is set to * to allow all requests, but there are security issues and not applicable in the case where the cookie is being sent.

Access-control-allow-credentials:

An optional field Boolean type that indicates whether cookies are allowed to be sent.

Access-control-expose-headers

Optional fields, the XMLHttpRequest object getResponseHeader () method can only get 6 basic fields in the Cors request, Cache-control, Content-language, Content-type, Expires, Last-modified, Pragma. If you need anything else, you need to specify here.

Client Cookie Issue:

The cors request does not send cookies and HTTP authentication information by default, and if a cookie is to be sent, in addition to the server-side authentication:

Access-control-allow-credentials:true

You also need to request to open the Withcredentials property, JS:

var xhr = new XMLHttpRequest ();
Xht.withcredentials = true;

In Fetch:

Options.headers = {
    credentials: ' Include ',
}
fetch (url,options)
not simple request

A non-simple cors request sends an options type of preflight (preflight) request prior to formal communication. The server adds some fields to the response header to inform the browser whether it can request or not.

A pre-check request is generally a options request, and the request header contains the following information: Origin request Source Access-control-request-method
What methods will the request use Access-control-request-headers
The field is a comma-delimited string that specifies the additional header information field that the browser cors request will send

Pre-Test Request response

    Access-control-allow-credentials:true
    Access-control-allow-headers:origin, No-cache, X-Requested-With, If-modified-since, Pragma, last-modified, Cache-control, Expires, Content-type,
    X-e4m-with,userid,token Access-control-allow-methods:post, GET, OPTIONS, DELETE
    access-control-allow-origin:http://demo.com.cn
    access-control-max-age:0
    Allow:get, head, POST, put, DELETE, TRACE, OPTIONS, PATCH
    content-length:0
    Content-type:text/html;charset=utf-8
    date:wed, Dec 2017 00:18:29 GMT
    server:apache-coyote/1.1
    Xdomainrequestallowed:1

Where the keyword field is access-control-allow-origin: ...
Represents a consent to a cross-domain request. If the server rejects a pre-check request, the field and related fields are not there. Java Web Configuration allows cors requests

Java-written server-side application configuration cors A lot of ways, the principle is similar, introduce a simple implementation: Manual writing Filter:

    public class Corsfilter implements filter{public void init (Filterconfig filterconfig) throws Servletexception { TODO auto-generated Method stub} public void Dofilter (ServletRequest request, Servletresponse Respo NSE, Filterchain chain) throws IOException, servletexception {//TODO auto-generated method stub httpse  
    Rvletresponse res = (httpservletresponse) response;
    HttpServletRequest req = (httpservletrequest) request;
    String origin = Req.getheader ("origin");  
       Res.setcontenttype ("Text/html;charset=utf-8");  
       Res.setheader ("Access-control-allow-origin", Origin);  
       Res.setheader ("Access-control-allow-methods", "POST, Get, OPTIONS, DELETE");  
       Res.setheader ("Access-control-max-age", "0"); Res.setheader ("Access-control-allow-headers", "Origin, No-cache, X-requested-with, If-modified-since, Pragma,  
       Last-modified, Cache-control, Expires, Content-type, X-e4m-with,userid,token "); Res.setheader ("Access-control-allow-credentials", "true");  
       Res.setheader ("xdomainrequestallowed", "1");  
    Chain.dofilter (request, response);
 public void Destroy () {//TODO auto-generated method stub}}

Registering filters in Web.xml:

    <filter>  
     <filter-name>cors</filter-name>  
     <filter-class> com.mysoft.filter.corsfilter</filter-class>  
    </filter>  
    <filter-mapping>  
     < filter-name>cors</filter-name>  
     <url-pattern>/*</url-pattern>  
    </filter-mapping > 

The fetch request must also be modified:

    Fetch (' Http://172.0.0.1:8000/api/getAllUser ', {method
        : ' POST ',
        body:params,
        mode: ' Cors ',
        Headers: {
            ' content-type ': ' Application/json ',
             credentials: ' Include ',
             Accept: ' Application/json ',
        }
      });

Mainly add mode: ' Cors '

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.