Common cross-domain problems and solutions in front-end development

introduction

In front-end development, cross-domain issues are a very common problem. This article will introduce in detail what cross-domain is, common cross-domain scenarios, and various commonly used cross-domain solutions.

What is cross-domain

Cross-domain refers to a web page or web application that initiates a request for resources under another domain name in the browser. Due to the browser's same-origin policy restrictions, such cross-domain requests will be intercepted by the browser.
The same origin policy refers to:

  • Homology means that only when the protocol, domain name, and port are exactly the same, they are considered to be of the same origin.
  • Web pages from different sources cannot read the content of the other web page or use the JS interface of the other web page due to security considerations.

Common cross-domain scenarios

  • In separate development of front-end and back-end, the front-end requests the back-end API
  • Use CDN to load third-party JS libraries
  • The front-end page embeds comments/sharing and other components of other websites
  • H5 page communicates with mini program/App

Commonly used cross-domain solutions

1. JSONscript tags are not restricted by the same origin policy and can implement JSON

<script>
function callback(data) {
      
      
  console.log(data);
}
</script>
<script src="http://other.com/api?callback=callback"></script>

2. CORS

CORS is also supported by W3.

let xhr = new XMLHttpRequest();
xhr.('GET', 'http://other.com/api');
xhr.send();

3. Nginx proxy

Use Nginx reverse proxy to implement cross-domain requests.

4. postMessage

Use iframe+postMessage to achieve cross-window communication.

5. window.name

Use the name attribute to transmit small data to achieve cross-source communication.

6. WebSocket

A protocol that supports cross-domain communication.


Each of the above methods has its own advantages. In actual development, the best solution needs to be selected based on the scenario. I hope this article can provide a reference for solving cross-domain problems!

Guess you like

Origin blog.csdn.net/weixin_46254812/article/details/132912554