What is cross-domain

Cross-domain means that the browser cannot execute scripts from other sites. It is caused by the same origin policy of the browser and is a security restriction imposed by the browser on JavaScript.

The same origin policy restricts the following behaviors:

  • Cookie, LocalStorage, and IndexDB cannot be read
  • DOM and JS objects cannot be retrieved
  • The Ajax request could not be sent

Cross-domain solutions

  1. The json cross-domain

How it works: JSONP cross-domain is actually a proxy pattern for JavaScript design patterns. Loading static resource files from different domain names in HTML pages with corresponding tags is allowed by browsers, so we can use this “criminal vulnerability” to cross domains. Generally, we can dynamically create a script tag and then request a reference url to achieve cross-domain communication

// Let script = document.createElement('script'); script.src = 'http://www.nealyang.cn/login?username=Nealyang&callback=callback'; document.body.appendChild(script); function callback(res) { console.log(res); }Copy the code

Disadvantages: Ability to resolve cross-domain, but intelligently implement GET requests

  1. CORS
  • ORS requires both browser and backend support. Internet Explorer 8 and 9 need to be implemented through XDomainRequest.
  • The browser will automatically carry out CORS communication, the key to achieve CORS communication is the back end. As long as the backend implements CORS, cross-domain is achieved.
  • To enable CORS, set access-Control-allow-Origin on the server. This attribute indicates which domain names can access resources. If a wildcard is set, all websites can access resources.
  1. document.domain
  • This mode can be used only when the secondary domain names are the same. For example, a.test.com and b.test.com are used in this mode.
  • Just add document.domain = ‘test.com’ to the page to indicate that the secondary domain is the same
  1. postMessage

This approach is often used to retrieve third-party page data embedded in a page. One page sends the message, and the other determines the source and receives the message

/ / messaging client window. The parent. PostMessage (' message ', 'http://test.com'); Var MC = new MessageChannel(); mc.addEventListener('message', (event) => { var origin = event.origin || event.originalEvent.origin; If (origin = = = 'http://test.com') {the console. The log (' validation by ')}});Copy the code
  1. Node agents cross domains

Node middleware realizes cross-domain proxy by starting a proxy server to realize data forwarding. It can also modify the domain name in the cookie in the response header by setting the cookieDomainRewrite parameter to realize cookie writing in the current domain and facilitate interface login authentication.

Build a proxy server with Node + Express + HTTP-proxy-middleware

6. Nginx proxy is cross-domain