02_ Cross domain problem summary

Keywords: Javascript Front-end html5 Ajax

Cross domain problem summary

1. Why is there a cross domain problem?

The reason is that the browser adopts the Same origin policy for security

2. What is homology strategy?

1. Homology strategy is composed of Netscape A well-known security policy is proposed, which is now supported by all JavaScript All browsers will use this strategy.
2. Web It is built on the basis of homology strategy. The browser is only an implementation of homology strategy.
3. The so-called homology, also known as the same domain, refers to: protocol, domain name( IP),The ports must be identical
   Namely: agreement, domain name( IP),Only when the ports are the same can they be regarded as in the same domain.

Note: an example of the rule is as follows (assuming that the existing website address is: http://study.cn)

3. Dangerous scenarios without homologous strategy:

Hazardous scenario:

One day, you just woke up and received an email saying that your bank account is at risk. Hurry to click www.yinghang.com to change your password. You hurry to click in. It is still a familiar bank login interface. You decisively enter your account password and log in to see if there is less money. You don't see clearly when you are sleepy. The bank website you usually visit is www.yinhang.com, but now You visited www.yinghang.com, and then you sent a text message. The money was gone. What did the phishing website do? It's probably the following idea:
The following code is waste code, which demonstrates the harm without homology strategy (actually):

<iframe id="baidu" src="https://www.baidu.com"></iframe>
<script type="text/javascript">
  const iframe = window.frames['baidu']
  const inputNode = iframe.document.getElementById('To enter sensitive information input of id')
  console.log(inputNode.value)
</script>

4. What are the limitations of non homology? That is, what can't you do when you cross domains

1. Cookie Cannot read;
2. DOM Not available;
3. Ajax The request could not get data

5. How to solve cross domain problems in development:

Comparison of several ways to send get requests:

1.form - not limited by the same origin policy

2.ajax -- restricted by the same origin policy

3. Browser address bar - not restricted by the same origin policy

4. < script SRC > - not limited by the same origin policy

1.JSONP solves the cross domain problem of sending requests:

It should be made clear that JSONP is not a technology, but the "crystallization of wisdom" of programmers (taking advantage of the feature that tag request resources are not limited by homology Policy)
JSONP requires the cooperation of front and rear end personnel.

About jsonp cross domain solution:

1. Principle: using the script tag to send requests is not limited by the same origin policy, so cross domain problems will not occur

2. Routine: dynamically build script nodes and issue get requests by using the src attribute of the nodes, thus bypassing the ajax engine

3. Disadvantages: (1) it can only solve the cross domain problem of get requests. (2) the back-end engineer must cooperate with the front-end

4. Note: there is a feeling that the front end defines functions and the back end "calls". The data returned by the back end is parsed and run in js format.

Front end page writing:

<body>
  <button id="btn">Button</button>
  <script type="text/javascript">
    var btn = document.getElementById('btn');
    btn.onclick = function () {
      //1. Create a script tag
      var script = document.createElement('script');
      //2. Define a function waiting to be called in advance
      window.getData = function (data) {
        console.log(data);//Get the data
      }
      //3. Specify the src address for the node and the name of the callback function
      script.src = 'http://localhost:3000/jsonp?callback=getData';
      //4. Add the script tag to the body to take effect
      document.body.appendChild(script);
      //5. Delete the script tag without affecting the overall DOM structure
      //document.body.removeChild(script);
    }
  </script>
</body>

jQuery typography

/*
  * 1.Define a function waiting to be called in advance
    2.Create a script node
    3.Specify the src address for the node and the name of the callback function
    4.Insert node into page
    Note: all the above steps are completed by the bottom layer of jquery
*/

// This is recommended
$('#btn').click(function () {
//Complete writing
$.ajax({
  url:'http://localhost:3000/test',
  method:'get',
  dataType:'jsonp', //This attribute controls the above 4 steps
  data:{name:'zhangsan',age:18},
  success:function (result) {
    console.log(result)
  },
  error:function (err) {
    console.log(err)
  }
})

//Simplified writing
/*$.getJSON('http://localhost:3000/test?callback=?',{name:'zhangsan',age:18},function (data) {
  console.log(data)
})*/
})

Back end writing:

app.get('/jsonp', (req, res) => {
  //Deconstruction assignment to obtain request parameters
  const {callback} = req.query
  //Go to the database to find the corresponding data
  const data = [{name: 'tom', age: 18}, {name: 'jerry', age: 20}];
  res.send(`${callback}(${JSON.stringify(data)})`);
})

2. Configure cors in the background to solve cross domain problems

1) what is CORS?

Cross origin resource sharing (CORS) is an official cross domain solution. It does not need to do any special operations on the client. It is completely processed in the server and supports get and post requests.

2) how does CORS work?

CORS tells the browser that the request is allowed to cross domains by setting a response header. After receiving the response, the browser will release the response.

with Node For example, add settings to the server Routing:
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63348');

3. Use proxy server

Tell the browser that the request allows cross domain. After receiving the response, the browser will release the response.

with Node For example, add settings to the server Routing:
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63348');

3. Use proxy server

For example: nginx etc.

Posted by samafua on Fri, 01 Oct 2021 16:43:03 -0700