Several ways to solve cross-domain ajax

Cross-domain problem occurs because:

  • Browser limitations, for security reasons. Reception can access the back-end, browser nosy newspaper cross-domain problem, but in fact have access to the back of the front desk.

  • Cross-domain protocol, domain name, a port is not the same any browser that it is the cross-domain.

  • XHR (XMLHttpRequest) request because ajax is XHR requests, the browser will capture cross-domain issues.

Solutions:

  • Let the browser does not limit, specify the parameters and let the browser do the check, but the method is not reasonable, it needs everyone to do the changes.

  • Do not make XHR requests, so even if the cross-domain, the browser does not complain, the solution is JSONP, create a dynamic script by issuing requests through script.

  • In the inter point of view: one is to be modified caller code plus the field that tells the browser, cross-domain support, support calls

  • By nginx proxy mode, in which the domain name requests a proxy addresses assigned to b domain.

Cross-domain solutions:

  • Callee resolved: In response to the first request to increase the specified field, tells the browser allows the caller. Request this solution is sent directly from the browser. ( Server-side implementation, NGINX configuration Apache configuration)

  • The caller Solution: This is a hidden cross-domain Settlement Act. This cross-domain requests are not sent directly from the browser, but forwarded from the middle of the past http server.

Set your browser does not limit:

  • Everyting you can use the software to search the browser's full path, use this path under dos switching cd C: \ Users \ Administrator \ AppData \ Local \ Google \ Chrome \ Application

  • Enter chrome --disable-web-security --user-data-dir = g: \ temp3 (g temp3 data storage disk file can be easily created)

Use jsonp solve:

  • Jsonp (JSON with Padding) is a json "use mode" that allows it to obtain information from other web domain name (website), that cross-domain data is read. Why do we need a special technique different domain (website) to access data from (JSONP) it? This is because the same-origin policy. Same-origin policy, it is a well-known security policy proposed by Netscape, now all JavaScript-enabled browsers will use this strategy.

  • The method of setting request distal ajax  dataType: " JSONP " JSONP: " the callback " Cache: to true

  • Background need to increase JsonpAdvice class

  • jsonp only supports GET
  • Require changes to the code server
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
    public JsonpAdvice() {
        // TODO Auto-Generated Stub constructor
         // This is the name of the needs and ajax in jsonp: "callback" set as 
       Super ( "callback" );
    }
}

 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <Title> cross-domain </ title>
    <script src="jquery-1.11.3.js"></script>
    <link rel="stylesheet" type="text/css" href="jasmine-2.8.0/jasmine.css">
    <script src="jasmine-2.8.0/jasmine.js"></script>
    <script src="jasmine-2.8.0/jasmine-html.js"></script>
    <script src="jasmine-2.8.0/boot.js"></script>
</head>

<body>
    <script>
        function get1() {
                $.getJSON("http://localhost:8080/test/get1").then(function (result) {
                    console.log(result);
                });
            }
            // Each test case timeout 
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 ;
          // prefix request interface //  HTTP: // localhost : 8080 / Test 
        var Base = "/ ajaxserverapache" ;
          // test module 
        describe ( "cross-domain ", function () { // test method 
            it (" jsonp request " , function (DONE) {
                 // the results returned by the server 
                var result;
                $.ajax({
                    url: base + "/get1",
                    dataType: "jsonp",
                    jsonp: "callback",
                    cache: true,
                    success: function (json) {
                        result = json;
                    }
                });
                // Because it is an asynchronous request, the need to verify setTimeout 
                setTimeout (function () {
                    expect(result).toEqual({
                        "data": "get1 ok"
                    });

                    // check completion notification frame jasmine 
                    DONE ();
                }, 100);
            });
        });
    </script>
</body>

</html>

filter solutions (the caller):

  • Type filter provided in the filter startup class springBoot

  • Set a specific filtering parameter information

@SpringBootApplication
public class AjaxserverApplication {
    public static void main(String[] args) {
        SpringApplication.run(AjaxserverApplication.class, args);
    }

    @Bean
    public FilterRegistrationBean registerFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.addUrlPatterns ( "/ *" );
         //   set filter custom class 
        bean.setFilter ( new new CrosFilter ());
         return the bean;
    }
}
public class CrosFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse res = (HttpServletResponse) response;

        HttpServletRequest req = (HttpServletRequest) request;

        String origin = req.getHeader("Origin");

        IF (! org.springframework.util.StringUtils.isEmpty (Origin)) {
             // with cookie time, origin must be fully matched, you can not use * 
            res.addHeader ( "Access-Control-the Allow-Origin" , origin);
        }

        res.addHeader("Access-Control-Allow-Methods", "*");
        String headers = req.getHeader("Access-Control-Request-Headers");

        // supports all custom header 
        IF (! Org.springframework.util.StringUtils.isEmpty (headers)) {
            res.addHeader("Access-Control-Allow-Headers", headers);
        }
        res.addHeader("Access-Control-Max-Age", "3600");
        // enable cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}

 

Guess you like

Origin www.cnblogs.com/haha66/p/12004178.html