Record a CORS pit step

Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

preface

One of the previous remote work content is to configure and implement cross-domain access to CORS, originally a very simple problem, but because of Spring’s encapsulation “pit” a little sad, and involving a cross-domain failure of Internet Explorer to deal with the problem is more troublesome, the following is the record and note for the solution of the whole CORS cross-domain question.

What is Ajax cross domain?

To put it simply, if ajax is used to access non-homogeneous resources such as IP addresses of different ports, cross-domain problems will occur. For example, the following urls will produce cross-domain problems.

  • http://www.example.com/dir2/other.htmlhomologous
  • http://example.com/dir/other.html: Different source (different domain name)
  • http://v2.www.example.com/dir/other.html: Different source (different domain name)
  • http://www.example.com:81/dir/other.html: Different source (different port)

The following is a cross-domain error message. If a cross-domain error occurs, we cannot access the related server resources, and usually give a message:

XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.xyz.com' is therefore not allowed access.
Copy the code

If a resource is cross-domain, the browser cannot retrieve the following information:

Cookie, LocalStorage, and IndexDB cannot be read.

(2) DOM cannot be obtained.

(3) AJAX requests cannot be sent.

Cross-domain is a common and slightly annoying problem in browsers. Before HTML5, it could only be solved by JSONP, but html5 has solved a lot of problems for Ajax cross-domain.

Common solutions

Common solutions are as follows:

  • Jsonp: Is usedJs callback functionIn the way of configuration such ashttp://xxxx.com?call=func()Can be used at this time<script></script>Label line wrap, and setsrcThe tag is sent to the server and then the callback function is parsed. There is also a way to use JSeval()Function call script code, of course, jSONP processing can only support get calls, too limited.
  • CORS is a mechanism that allows resources in the current domain (such as HTML/JS/Web service) to be accessed by scripts in other domains.

Since HTML5 has added cORS support, and there is almost no web page that is not HTML5 now, finally we can use CORS solution, jSONP way can basically forget.

Hit the pit reason

Since everyone’s project environment is different, here are only the problems encountered in the configuration of the individual environment.

  1. If there isweb.xmlConfiguration: Any other configuration is ignored during access and only takes effectxmlconfiguration
  2. The configuration in the project allows post to be invalidated across domains and only GET to be accessed across domains, for unknown reasons, perhaps by fortress?

To solve the process

  1. Join in the request@crossxxxNote, found invalid
  2. Make the request specificRequestMethod.GETorPOSTFound the same thing
  3. I ended up using the Spring CORS solution, but realized that it wasn’t enough to just add an annotation

Refer to the blog

There are many reference solutions for blogs on the web

Segmentfault.com/a/119000001… Segament is a great blog.

Other information:

www.imooc.com/qadetail/30… www.jianshu.com/p/f3840c8c0… Brief introduction to CORS

Blog.csdn.net/doujinlong1… [Business knowledge — Logger log printing specification]

www.cnblogs.com/doit8791/p/… [Talk about log printing specifications] Take time to look at it while developing

The solution

The solution is to use the Spring-style configuration

Configuration after change

  1. usepom.xmlAdd new dependencies and use Cors’ native support

To configure the JAVA background, follow the following steps:

  • Step 1: Get the dependent JAR package

    Jar, java-property-utils-1.9.jar and put them in the lib directory. (Put it under the corresponding project’s webContent/web-INF /lib/)

  • Step 2: If your project is built using Maven, add the following dependencies to POM.xml:

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>[ version ]</version>
</dependency>
Copy the code

The version should be the latest stable version,CORS filter

  1. Add the following configuration to web. XML

  2. A more detailed description of the configuration is available on the blog mentioned above

Here is the configuration information related to web.xml.

<! - cross domain configuration: reference > http://www.thomasyoung.cn/fontend/2017/04/01/ajax-session/--
    <filter>
        <! -- Native Cors filter configuration -->
        <filter-name>CorsFilter</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

        <! -- Whether non-cross-domain requests can pass this filter, default is true; If set to false, only cross-domain requests are allowed -->
        <init-param>
            <param-name>cors.allowGenericHttpRequests</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>http://192.168.92.190:8080, http://192.168.92.145:8080,</param-value>
        </init-param>
        <! -- Whether requests from subdomains of allowOrigin are allowed. It should be clear that www.example.com is the subdomain name of example.com -->
        <init-param>
            <param-name>cors.allowSubdomains</param-name>
            <param-value>false</param-value>
        </init-param>
        <! -- cors.allowed.methods -->
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
        </init-param>
        <! -- cors.allowed.headers -->
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>

        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <! Here you can add your own exposed Headers -->
            <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
        </init-param>
        <! The credentials in cors.support.credentials -->
        <init-param>
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>
        <! -- cors.preflight.maxage Maximum cache time -->
        <init-param>
            <param-name>cors.maxAge</param-name>
            <param-value>10</param-value>
        </init-param>
    </filter>
  
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
Copy the code

Internet Explorer 8/ Internet Explorer 9 solves the access denial problem

Because of this problem when the request can be compatible with IE, so through consulting a variety of network information found the following some references.

The first is to import JS files

By introducing the following js, IE will be able to support some of the missing underlying methods that jquery calls.

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js" type="text/javascript" charset="utf-8"></script>
Copy the code

Second: Jquery enables cross-domain mode

If you are using jquery you may need to use the following Settings to allow cross-domains before sending a request, but not always.

jQuery.support.cors = true
Copy the code

conclusion

More is the temporary note processing of problems encountered in work, CORS basic information can be quickly mastered, HTML5 after the emergence of CORS to solve a lot of problems.