What is cross-domain

There is a difference between the domain name, protocol and port of the browser as the requestor and the requested party, which is called cross-domain.

What problems does cross-domain cause

  • The Ajax request is intercepted by the browser
  • Caches such as cookie, Storage, and indexDB cannot communicate with each other

So why cross-domain? It starts with homology.

What is the Same Origin Policy?

If the domain name, protocol, and port of the two urls are the same, the two urls are called same-origin. Same-origin is a browser security restriction. By default, only two sites with the same origin can access data from each other. If there is no same-origin restriction, cookies can be shared between different websites, and attackers can directly obtain cookies to launch CSRF (cross-site request forgery) attacks. The interface is invoked casually, resulting in data leakage or deletion.

Cross-domain solutions

Cross-domain solutions include: tags such as Script, JSONP, iframe, Node request forwarding, CORS, nginx reverse proxy, etc

Img, link, script tags

Img, link, and script tags use the SRC or href attribute to access cross-domain resources, usually CDN resources and third-party package resources.

<img src="xxx" />
<link href="xxx" />
<script src="xxx"></script>
Copy the code

jsonp

Jsonp is a variant of script tag cross-domain, requesting data across domains by adding the callback field after the SRC attribute of the script tag.

  • The client
<script>
  function getMenuData(data) {
    // Render the menu according to data
  }
</script>
<script src="http://www.a.com/data?callback=getMenuData"></script>
Copy the code
  • The service side
MenuData({ status: "success".data: ["menu1"."menu2"]});Copy the code

The client and server make data conventions during development, and since it only supports GET requests, usage scenarios are few and far between.

iframe

The postMessage approach to iframes naturally supports cross-domain communication, and pages inside and outside the iframe can use urls from different sources.

  • The parent page www.a.com
<iframe src="www.b.com"
  ><iframe>
    <script>
      window.addEventListener("message".function (event) {
        console.log(event.data);
      });
    </script></iframe
  ></iframe
>
Copy the code
  • Child pages www.b.com
window.postMessage(message, "http://www.a.com");
Copy the code

Nodejs requests forwarding

Use NodeJS to create a relay server. Requests are forwarded to the target address by accessing node Server, breaking cross-domain restrictions. From the beginning:

A => C A Request C A <= C C Response ACopy the code

To:

A => B => C A requests B, B requests C A <= B <= C C responds to B, B responds to ACopy the code
var koa = require("koa");
var proxy = require("koa-proxy");
var app = koa();
app.use(
  proxy({
    host: "http://www.a.com".// The final API address to access})); app.listen(3000);
Copy the code

Tips: Same-origin policy is a browser restriction, not a server restriction. This approach is often used in development situations where the back end does not provide cross-domain support and the front end resolves the cross-domain limitations. Now that webpack-dev-server has its own proxy, you do not need to start additional servers by yourself, just add configuration, as follows:

    '/api': {
        target: 'https://http://123.123.123.1:8080'.changeOrigin: true.secure: false.pathRewrite: {
          '^/api': '/api'}}Copy the code

cors

Cors is a server configuration. After cross-domain resource requests are configured, server resources can be requested by cross-domain requests. The main response headers are as follows:

  • Access-control-allow-origin Specifies the domain names that can be accessed
  • Access-control-allow-methods Methods that Allow requests
  • Access-control-allow-headers Specifies the header that allows the request
  • Access-control-allow-credentials Indicates whether cookies are allowed

It is important to note that the server needs to process requests for the options method separately after setting CORS.

What is an options request

An options request is a prying request made by the browser. When sending a simple request, the browser will not generate a snooping request. When sending a complex request, the browser will first send a sniffing request with the method of options. The real request will be sent only after the successful return of the snooping request. The purpose of the sniffer request is to send the method used in the actual request and the header field that will be carried to the server in advance to prevent side effects on the server data. Options Specifies the header generated by the request

Origin: http://www.client.com access-control-allow-methods: Put... Access - Control - Allow - Headers: the content-type...Copy the code
  • Simple request A request that satisfies the following conditions:

    1. The request method can be HEAD, GET, or POST.

    2. Request headers should not exceed the following:

  • Accept
  • Accept-Language
  • Content-Language
  • The content-type: application/x – WWW – form – urlencoded | | multipart/form – data | | text/plain
  • DPR
  • Downlink
  • save-Data
  • ViewPort-Width
  • Width
  1. None of the XMLHttpRequestUpload objects in the request are registered with any event listeners
  2. No ReadableStream object is used in the request.
  • Complex request A request that is in addition to the simple request above

Nginx reverse proxy

Nginx reverse proxy means that when the client accesses the server path/API address, the server will proxy the requests under the path/API to the specified service. The principle is the same as the request forwarding implemented by using nodeJS.

    location /api/ {
        proxy_pass http:/ / 123.123.123.1:8080 / API /;
        index index.html index.htm;
    }
Copy the code

tips

Cross-domain and homology are not difficult, but they need to be able to combine theories to solve everyday problems: for example

  1. Access to XMLHttpRequest at ‘xxx’ from origin ‘xxx’ has been blocked by CORS policy: No ‘access-control-allow-Origin’ header is present on the requested resource

  2. Mixed content: the page at ‘www.xxx.com/’ was loaded over HTTPS, but resquested an insecure prefetch resource ‘www.ooo.com/’. This content should also be served over HTTPS You can quickly understand that this is a browser security limitation.

  3. Will all complex requests initiate an options probe request?

No, the options request can set the cache time, and will not send probe requests until it expires

Access-Control-Max-Age: time
Copy the code

There’s a lot more about browser security restrictions and iframe communication between parent and child pages. Comments and likes are welcome. This article is [JS Foundation] series of articles, pay attention to the little sister, learn a study together!