5 kinds of solutions [turn] to solve the problem of cross-domain ajax

Editor:

 

What is cross-domain problem?
Cross-domain JavaScript issues from the "same origin policy" that only agreements + hostname + port number (if present) are the same, allow mutual access. That JavaScript can access and manipulate resources under their own domain, you can access and manipulate resources in other domains. Cross-domain issue is for the JS and ajax, html does not have cross-domain problem.

View Browser Developer Tools Console error:

Failed to load http://a.a.com:8080/A/FromServlet?userName=123: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://b.b.com:8080' is therefore not allowed access.

http://www.abc.com/a/b call http://www.abc.com/d/c (non-cross-domain)

http://www.abc.com/a/b call http://www.def.com/a/b (cross-domain: domain name inconsistency)

http://www.abc.com:8080/a/b call http://www.abc.com:8081/d/c (cross-domain: Port inconsistent)

http://www.abc.com/a/b call https://www.abc.com/d/c (cross-domain: different protocols)

Please note: localhost 127.0.0.1 and although point to the machine, but also a cross-domain.

 

 

Cross-domain problem how to solve?
1, allows access response header added Header

2, jsonp supports only get request does not support the post request

3. Internal httpClient forward

4, using an interface gateway --nginx, springcloud zuul (Internet company conventional solutions)

 

1 solution: Add Header response headers allow access to
Cross-Origin Resource Sharing (CORS) Cross-Origin Resource Sharing

The security infrastructure solutions for cross-domain access is based on the "JavaScript can not control the HTTP header"

It requires authorization whether to allow cross-domain access by the target domain returned HTTP header.

response.addHeader ( 'Access-Control-Allow -Origin: *'); // allow access to all sources
response.addHeader ( 'Access-Control-Allow -Method: POST, GET'); // allow access manner


 

Solution 2: jsonp supports only get request does not support the post request
Usage:

①dataType changed jsonp    

②jsonp: "jsonpCallback" ---- sent to the back-end is actually http:? // aacom / a / FromServlet userName = 644064 & jsonpCallback = jQueryxxx     

③ get rear acquisition request jsonpCallback    

④ construction callback structure

.ajax $ ({
of the type: "GET",
the async: false,
url: "HTTP:? // aacom / A / fromServlet userName = 644 064",
dataType: "JSONP", // data type JSONP
JSONP: "jsonpCallback" , // service parameters for receiving calls callback function name
Success: function (Data) {
Alert (Data [ "the userName"]);
},
error: function () {
Alert ( 'Fail');
}
}) ;
 

// rear
String jsonpCallback = request.getParameter ( "jsonpCallback");
// constructor callback format jsonpCallback (data)
. Resp.getWriter () the println (jsonpCallback + "(" + jsonObject.toJSONString () + ")");
the principle JSONP
in same-origin policy, a page at a server is unable to obtain the data other than the server, that is not the general cross-domain ajax request. However, img, iframe, script and other labels exception, these labels can be the data on request to the other servers by src attribute. Using the <script> tag's open strategy, we can achieve cross-domain requests data, of course, need to meet the server side. Jquery ajax in the core is to obtain non-content on this page by XmlHttpRequest, while the core jsonp is dynamically added <script> tag to call js script server.

  When we normally a JSON data request, the server returns a string data type JSON, JSONP model we use when requesting data returned from the server is a piece of executable JavaScript code. Because cross-domain dynamic loading jsonp principle is to use the <script> of src, so we can only url parameter passed by the way, so jsonp of type type can only get!

Example:

$.ajax({

    url: 'http://192.168.10.46/demo/test.jsp', // different domains

    type: 'GET', // jsonp mode only GET is legal

    data: {

        'action': 'aaron'

    },

    dataType: 'jsonp', // Data type

    jsonp: 'jsonpCallback', // specify a callback function name, and received the same server, and return back

})

In fact, the interior will be transformed into jquery

http://192.168.10.46/demo/test.jsp?jsonpCallback=jQuery202003573935762227615_1402643146875&action=aaron

Then dynamically load

<script type="text/javascript"src="http://192.168.10.46/demo/test.jsp?jsonpCallback= jQuery202003573935762227615_1402643146875&action=aaron"></script>

Then executes rear jsonpCallback (parameter passing), the data sent through argument form.

  Requesting data pattern using JSONP entire process: The client sends a request, the name of an executable prescribed function (this is done jQuery package handling, automatic callback and help you generate the data taken out to invoke property methods for success , and a callback handler is not passed), the server accepted the jsonpCallback function name, and then sent through the data in the form of arguments

 

(Jquery in source code, JSONP implementations are dynamically added <script> tag to invoke .jquery js script provided by the server loads a global object window function, when the <script> When the function execution code inserting, finished it <script> will be removed. jquery same time also for non-cross-domain request has been optimized, if the request is under the same domain name then he will work just like a normal Ajax request.)

 

Solution 3: httpClient internal forwarding
The principle is very simple, if you want to visit the site in the B A site to obtain the results by Ajax, although there is cross-domain ajax problem, but visit site B in B sites get results, there is no cross-domain problem, in this manner actually HttpClient B site ajax request access to site B, and then forwards the data request to obtain the results of the a sites by HttpClient. However, this approach had two requests, low efficiency, but the internal request packet capture tools can not analyze security.

$.ajax({
type : "GET",
async : false,
url : "http://b.b.com:8080/B/FromAjaxservlet?userName=644064",
dataType : "json",
success : function(data) {
alert(data["userName"]);
},
error : function() {
alert('fail');
}
});
 

@WebServlet ( "/ FromAjaxservlet")
public class FromAjaxservlet the extends the HttpServlet {


protected void the doGet (the HttpServletRequest REQ, the HttpServletResponse RESP) throws ServletException, IOException {
the try {
// create a default connection
CloseableHttpClient httpClient HttpClients.createDefault = ();
// Create Object HttpGet processing requests get forwarded to the A site
HttpGet HttpGet = new new HttpGet ( "HTTP: // aacom: 8080 / A / fromServlet userName =?" + req.getParameter ( "userName"));
// execute
CloseableHttpResponse response = httpClient. Execute (HttpGet);
int code = response.getStatusLine () getStatusCode ();.
// Get status
System.out.println ( "http request results:" + code);
IF (code 200 is ==) {
// Get a site results returned
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
//把结果返回给B站点
resp.getWriter().print(result);
}
response.close();
httpClient.close();
} catch (Exception e) {
}
}
}
 

4 solution: using nginx to build enterprise-level interface gateway mode
www.aacom not directly requested content www.bbcom may, in accordance with the domain name, but a different project names are distinguished by nginx. What does that mean? That might somewhat abstract. Suppose we call www.nginxtest.com company domain

When we need to access www.aacom accessed through www.nginxtest.com/A, and forwarded to www.aacom by nginx

When we need to access www.bbcom accessed through www.nginxtest.com/B, and forwarded to www.aacom by nginx

We visit the company's domain name is "homologous", but a different project name, project name of the role this time just to differentiate, to facilitate forwarding. If you do not understand the words, look at how I configured it:

{Server
the listen 80;
server_name www.nginxtest.com;
LOCATION / {A
proxy_pass HTTP: // aacom: 81;
index index.html index.htm;
}
LOCATION / B {
proxy_pass HTTP: // bbcom: 81;
index index. index.htm HTML;
}
}
we begin with a visit www.nginxtest.com URL and port 80, nginx will intercept match, if the project called a, then distributed to aacom: 81. In fact distinguished by "homologous" domain name, a different project name, matching intercepted by nginx, forwarded to the corresponding URL. The whole process, two requests, requesting the first server nginx, nginx second server corresponding to the URL distributed by intercepting matching.

 

5 solution: Use Spring Cloud zuul Gateway Interface
 

Guess you like

Origin www.cnblogs.com/yoyo008/p/11390519.html