Now let’s discuss the related issues of browser cross-domain request data. It may not be very standard to say that this is because rejecting cross-domain request data is not unique to the browser. The reason why cross-domain cannot request data is because browsers basically implement a security specification called "same-origin policy". What is the specific specification? We found a profile on MDN with the following address:
Explanation of browser homologous policy
In general, when URL A and URL B differ in terms of protocol, port, and domain name, the browser will initiate a same-origin policy and refuse data requests between servers A and B.
When talking about the same-original strategy, the knowledge you get is shallow. You must practice it yourself. How does the same-original strategy be reflected? Below I will demonstrate step by step in combination with the code.
1. Server A cannot request server B
Since it is cross-domain, I'll assume that I have two domain names, namely A and localhost. A means that the editor hosts the domain name on Alibaba Cloud. Localhost, as the name suggests, is my development machine. We imagine a scenario where we deploy an index.html file on localhost, a simple spring-boot backend service on server A, and provide a simple interface to expose it to the index.html file call. Finally, the browser requests the index.html file of localhost, and see what the browser prompts?
index.html
<!DOCTYPE html><html><head><title>Test cross-domain access</title><meta charset="utf-8"/></head><body> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $.ajax({ type : "get", async : true, url : "http://A/hello/map/getUser.json",// Request interface type on server A: "json", success : function(data) { // Print the returned data console.log("success,and return data is " + data); } }); }); </script> <h2>hello world</h2></body></html>Request the index.html file on the browser, and it is displayed as follows:
It can be found that the request was rejected by the browser, prompting us not to allow cross-domain requests. It is very uncomfortable. How to solve it?
2. Use jsonp to resolve cross-domain requests
First, let’s talk about the principle. JSONP solves cross-domain problems mainly utilizes the cross-domainability of the <script> tag, that is, the feature that the link address in the src attribute can be accessed across domains, because we often set the src attribute value to the address of cdn, and the relevant js library has been loaded.
index.html
<!DOCTYPE html><html><head><title>Test cross-domain access</title><meta charset="utf-8" /></head><body> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $.ajax({ type : "get", async : true, jsonp : "callbackName",// Backend interface parameter name jsonpCallback : "callbackFunction", // Callback function name url : "http://A/hello/map/getUser.json", dataType : "jsonp", // The data format is jsonp success : function(data) { console.log("success"); } }); }); </script> <script type="text/javascript"> var callbackFunction = function(data) { alert('The data returned by the interface is: ' + JSON.stringify(data)); }; </script></body></html>The interface code on the A server is:
/** * * The class JsonBackController. * * Description: The controller returns a string of simple json data, and the json data is composed of a simple User object* * @author: huangjiawei * @since: June 12, 2018* @version: $Revision$ $Date$ $LastChangedBy$ * */@RestController@RequestMapping(value = "/map")public class JsonBackController { private static final Logger logger = LoggerFactory.getLogger(JsonBackController.class); /** * Resolve cross-domain request data* @param response * @param callbackName Front-end callback function name* @return */ @RequestMapping(value = "getUser.json") public void getUser(HttpServletResponse response, @RequestParam String callbackName) { User user = new User("huangjiawei", 22); response.setContentType("text/javascript"); Writer writer = null; try { writer = response.getWriter(); writer.write(callbackName + "("); writer.write(user.toString()); writer.write(");"); } catch (IOException e) { logger.error("jsonp response write failed! Data: " + user.toString(), e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { logger.error("Output stream close exception!", e); } writer = null; } } }}The backend passes in a parameter callbackName callback function name, and then returns a piece of js code to the frontend. The js code format is as follows:
callbackName + ( data ) + ;
The browser requests the index.html file on the localhost server, and the result is as follows:
The above method solves cross-domain problems through jquery + jsonp. Didn’t you just say that you can use the src attribute of the <script> tag? Four.
index.html on localhost server
<!DOCTYPE html><html><head><title>Test cross-domain access</title><meta charset="utf-8" /></head><body> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> var callbackFunction = function(data) { alert('The data returned by the interface is: ' + JSON.stringify(data)); }; </script> <script type="text/javascript" src="http://A/hello/map/getUser.json?callbackName=callbackFunction"></script></body></html>The browser display effect is the same as above. But it should be noted here that src means introducing a js file. Since it is called directly by the interface, and the data returned by the interface happens to be a piece of js code, it can be executed. In addition, the order of the second <script> tag cannot be reversed, otherwise the callbackFunction function will not be found.
Project code address: https://github.com/SmallerCoder/jsonpDemo
Finally, we will summarize that there are many solutions to cross-domain solutions, and jsonp is just one of them, and the specific situation needs to be analyzed in detail. I hope this article will be helpful to you. Thank you for reading. Welcome to github to start, Momo! I also hope everyone will support Wulin.com more.