Cross-domain is a word that comes up in front end developers, whether you’re on the job or in an interview. Especially when you’re initially building a project. But simply memorizing several plans for the interview is not important. It is important to have a thorough understanding of the cause and effect of cross-domain, as well as the most convenient and quick solution at present, which is the best policy. Instead of looking up a few articles on the Internet and seeing the project configured and the problem solved and then forgetting about it. Although the day can be mixed as usual, but the next time you encounter this problem is a disorderly search, the efficiency is not high, the interview is also to find all kinds of information to understand.
In order to fully understand the cross-domain past life, thoroughly understand this thing! Hence the article.
Why does cross-domain exist
Cross-domain problems occur because of the browser same-origin policy. So why do browsers have cross-domain limitations? In fact, it is not hard to imagine that the main purpose of cross-domain restriction is for the user’s Internet security.
Two dangerous scenarios without the same-origin policy restriction
What security issues exist if browsers do not have same-origin policies. The following uses DOM same-origin policy and XMLHttpRequest same-origin policy as examples:
If there is no DOM same-origin policy, that is, iframes of different domains can access each other, then hackers can attack like this:
- Create a fake website that uses iframe to nest a bank website
http://mybank.com
. - Adjust the width and height of the iframe to the entire page, so that users come in just like the bank’s website, except for the domain name.
- At this point, if the user enters the account password, our main website can be accessed across domains
http://mybank.com
Dom node, you can get the user account password.
If XMLHttpRequest has the same origin policy, then a hacker can carry out a CSRF (cross-site request forgery) attack:
- The user logs in to his bank page
http://mybank.com
.http://mybank.com
Add the user id to the user’s cookie. - Users browse malicious pages
http://evil.com
Executes the malicious AJAX request code in the page. http://evil.com
向http://mybank.com
When making an AJAX HTTP request, the request will default tohttp://mybank.com
The corresponding cookie is sent at the same time.- The bank page extracts the user id from the cookie sent, verifies that the user is correct, and returns the request data in response. That’s when the data gets leaked.
- And because Ajax is executed in the background, the user is unaware of the process.
Therefore, with the same origin policy, we can be more secure online.
The same origin policy of the browser
The Same Origin Policy (SOP) is an important security Policy that restricts how documents from one Origin or scripts loaded by it can interact with resources from another source. The same origin policy of the browser prevents client scripts (such as Java) from making cross-site calls (usually using requests) to services in different domains to prevent cross-site scripting attacks. It can help block malicious documents and reduce the number of vectors that can be attacked. This is a key security mechanism for isolating potentially malicious files. The same origin policy mechanism is a convention. It is the core and most basic security function of the browser. Normal browser functions may be affected. The Web is built on the same origin policy, and browsers are just an implementation of the same origin policy.
The same origin policy is the core and most basic security function of the browser. If the same origin policy is absent, the normal functions of the browser may be affected. For example, the JS of source A cannot read or set the element attributes of source B.
Definition of homology
The so-called homology refers to that two pages have the same domain name, protocol, and port.
Problems caused by the same-origin policy
- The same owner of the same level domain, but different level 2 domain is restricted (cookies, LocalStorage, IndexDB read)
- AJAX requests cannot be sent across domains
- Unable to manipulate DOM
- Q: Why can Form forms send requests across domains, but AJAX can’t? A: Because the page is refreshed after the Form is submitted, the data cannot be retrieved even if it crosses domains, so the browser considers this safe. The biggest advantage of AJAX is that you can update parts of a web page without reloading the entire page. If you make it cross domains, you can read private information about the destination URL, which can become very dangerous, so browsers don’t allow AJAX to send requests across domains.
Cross-domain principles
Cross-domain means that the browser cannot execute scripts from other sites. It is caused by the same origin policy of the browser. The same origin policy is a security restriction imposed by browsers on JavaScript. Any difference in protocol, domain name, or port is considered as a different domain. The cross-domain principle is to circumvent browser security restrictions in various ways.
Cross-domain solutions
In the initial project, JSONP was used, but there were some problems, such as insecure use of GET request and small data carried. Later, IFrame was also used, but only the primary domain was the same, and there were also some problems. Later, through understanding and learning, I found that it was convenient to use proxy and proxy together. Guide the background according to this way to do the server configuration, in the development of proxy, the use of nginx proxy on the server, so that the development process is convenient to each other, high efficiency; Windows.postmessage () is now available in H5.
- JSONP:\
Jsonp(JSON with Padding) is a “usage mode” of JSON that allows web pages to fetch data from other domains.
Ajax requests are not allowed to make cross-domain requests due to the same origin policy, whereas the link in the SRC attribute of the script tag can access cross-domain JS scripts. With this feature, the server no longer returns JSON data, but returns a piece of JAVASCRIPT code that calls a function. The call is made in SRC, which is cross-domain.
Step: 1. Create a script tag. 2. Interface parameter, must have a custom function name, otherwise background cannot return data 4. Accept the returned data by defining the function nameCopy the code
// Create script dynamically
var script = document.createElement('script');
// Set the callback function
function callbackFunction(data) {
console.log(data);
}
// Set the SRC property of the script and set the request address
script.src = 'https://api.ycsnews.com/test?callback=callbackFunction';
// make script work
document.body.appendChild(script);
Copy the code
Laravel PHP backend code
public function test(Request $request){
// Get the callback function name
$callback= $request->callback;
// The server returns data
$data= [['code'= >0.'data'= > [1.2.3.4.5]]];// Execute the callback function dynamically
/ / method 1:
return response()->jsonp($callback.$data);// The name of the received method and the data transferred
/ / method 2:
// return response()->json($data)->setCallback($callback);
}
Copy the code
The disadvantage of the jsonJSON only supports GET, because script tags can only use GET requests; JSONP requires backend coordination to return data in the specified format.
-
Document. domain The base domain name is the same as the subdomain name
-
Window. name uses a browser window to load all domain names that share a window.name
-
CORS Cross-origin Resource Sharing (CORS) Server Settings The principles of CORS are as follows: After the access-Control-allow-Origin HTTP response header is set on the server, the browser allows cross-domain requests. The key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication is possible.
-
Proxy Indicates the common proxy mode. In plain English, there is a cross-domain problem when a client browser makes a request, but there is no cross-domain problem when a server makes a request to another server, because the cross-domain problem is ultimately due to the same origin policy, which only exists in the browser
So we can configure a proxy server through Nginx, reverse proxy access cross-domain interface, and we can also modify the Cookie domain information, convenient for the current domain Cookie write
-
Window.postmessage () takes advantage of the new H5 feature window.postmessage ()
-
Websocket
Cross-domain configuration
Vue-various configurations of agents in the CLI
Vue-cli is based on Webpack, which uses webpack-dev-server to start scaffolding locally, that is, to start a Node service locally, to monitor and package static resources in real time, because they are packaged, only need to configure. We configure the proxy in vue.config.js as follows, which can be written in many ways
module.exports = {
/ /...
devServer: {
proxy: {
'/api': 'http://www.hahaha.com'}}} copy the codeCopy the code
As shown above, when you request/API/ABC interface will be acting to http://www.hahaha.com/api/abc