Home > Article > Web Front-end > How to solve ajax cross-domain problem
Solution to ajax cross-domain problem: 1. Add Header to the response header to allow access; 2. jsonp only supports get requests but not post requests; 3. httpClient internal forwarding; 4. Use nginx to build an enterprise-level interface gateway Way.
Related free learning recommendations: ajax (Video )
Solution to ajax cross-domain problem:
Solution 1: Add Header to the response header to allow access
Cross-Origin Resource Sharing (CORS) Cross-Origin Resource Sharing
The security foundation of this cross-domain access solution is based on "JavaScript cannot control this HTTP header"
It It is necessary to authorize whether to allow cross-domain access through the HTTP header returned by the target domain.
response.addHeader(‘Access-Control-Allow-Origin:*’);//允许所有来源访问 response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方式
Solution 2: jsonp only supports get requests but not post requests
Usage: ①Change dataType to jsonp ②jsonp: "jsonpCallback"— ——The actual value sent to the backend is http://a.a.com/a/FromServlet?userName=644064&jsonpCallback=jQueryxxx ③The backend obtains the jsonpCallback in the get request ④Construct the callback structure
$.ajax({ type : "GET", async : false, url : "http://a.a.com/a/FromServlet?userName=644064", dataType : "jsonp",//数据类型为jsonp jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数 success : function(data) { alert(data["userName"]); }, error : function() { alert('fail'); } }); //后端 String jsonpCallback = request.getParameter("jsonpCallback"); //构造回调函数格式jsonpCallback(数据) resp.getWriter().println(jsonpCallback+"("+jsonObject.toJSONString()+")");
JSONP implementation Principle
Under the same-origin policy, pages under a certain server cannot obtain data outside the server, that is, general ajax cannot make cross-domain requests. However, tags such as img, iframe, and script are exceptions. These tags can request data on other servers through the src attribute. Using the open policy of the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, we can request data across domains. Of course, this requires the cooperation of the server. The core of ajax in Jquery is to obtain non-this page content through XmlHttpRequest, while the core of jsonp is to dynamically add the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag to call the js script provided by the server.
When we normally request a JSON data, the server returns a string of JSON type data, and when we use the JSONP mode to request data, the server returns an executable JavaScript code. . Because the cross-domain principle of jsonp is to dynamically load the src of <script>, we can only pass the parameters through the url, so the type of jsonp can only be get! </script>
Example:
$.ajax({ url: 'http://192.168.10.46/demo/test.jsp', //不同的域 type: 'GET', // jsonp模式只有GET 是合法的 data: { 'action': 'aaron' }, dataType: 'jsonp', // 数据类型 jsonp: 'jsonpCallback', // 指定回调函数名,与服务器端接收的一致,并回传回来 })
In fact, jquery will be converted internally to
http://192.168.10.46/demo/test.jsp?jsonpCallback=jQuery202003573935762227615_1402643146875&action=aaron
Then dynamic loading
<script type="text/javascript"src="http://192.168.10.46/demo/test.jsp?jsonpCallback= jQuery202003573935762227615_1402643146875&action=aaron"></script>
Then the backend will execute jsonpCallback (pass parameters) and send the data in the form of actual parameters.
The entire process of using JSONP mode to request data: the client sends a request and specifies an executable function name (here jQuery does the encapsulation process and automatically generates a callback function for you and takes out the data For the success attribute method to call, instead of passing a callback handle), the server accepts the jsonpCallback function name, and then sends the data out in the form of actual parameters
(in jquery In the source code, jsonp is implemented by dynamically adding the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag to call the js script provided by the server. jquery will load a global function in the window object. When the 3f1c4e4b6b16bbbd69b2ee476dc4f83a code is inserted, the function will be executed. After execution, 3f1c4e4b6b16bbbd69b2ee476dc4f83a will be removed. At the same time, jquery has also optimized non-cross-domain requests. If the request is under the same domain name, it will work like a normal Ajax request.)
Solution 3: httpClient internal forwarding
The implementation principle is very simple. If you want to access site A through Ajax in site B to obtain results, there will of course be an ajax cross-domain problem. , but there is no cross-domain problem when accessing site B to obtain results in site B. This method is actually to access the HttpClient of site B through ajax in site B, and then forward the request through HttpClient to obtain the data results of site A. However, this method generates two requests, which is inefficient. However, internal requests cannot be analyzed by packet capture tools and are safe.
$.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 extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { //创建默认连接 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建HttpGet对象,处理get请求,转发到A站点 HttpGet httpGet = new HttpGet("http://a.a.com:8080/A/FromServlet?userName="+req.getParameter("userName")); //执行 CloseableHttpResponse response = httpClient.execute(httpGet); int code = response.getStatusLine().getStatusCode(); //获取状态 System.out.println("http请求结果为:"+code); if(code == 200){ //获取A站点返回的结果 String result = EntityUtils.toString(response.getEntity()); System.out.println(result); //把结果返回给B站点 resp.getWriter().print(result); } response.close(); httpClient.close(); } catch (Exception e) { } } }
Solution 4: Use nginx to build an enterprise-level interface gateway method
www.a.a.com cannot directly request the content of www.b.b.com , you can use nginx to distinguish them based on the same domain name but different project names. What does that mean? That may be a bit abstract. Assume that our company domain name is www.nginxtest.com
When we need to access www.a.a.com through www.nginxtest.com/A, and forward it to www.a.a.com
through nginx We need to access www.b.b.com through www.nginxtest.com/B, and forward it to www.a.a.com through nginx
When we access the company's domain name, it is "same source", but the project name is different , the role of the project name at this time is just to distinguish and facilitate forwarding. If you still don’t understand, first take a look at how I configured it:
server { listen 80; server_name www.nginxtest.com; location /A { proxy_pass http://a.a.com:81; index index.html index.htm; } location /B { proxy_pass http://b.b.com:81; index index.html index.htm; } }
我们访问以www.nginxtest.com开头且端口为80的网址,nginx将会进行拦截匹配,若项目名为A,则分发到a.a.com:81。实际上就是通过"同源"的域名,不同的项目名进行区分,通过nginx拦截匹配,转发到对应的网址。整个过程,两次请求,第一次请求nginx服务器,第二次nginx服务器通过拦截匹配分发到对应的网址。
相关免费学习推荐:javascript(视频)
The above is the detailed content of How to solve ajax cross-domain problem. For more information, please follow other related articles on the PHP Chinese website!