Day 21 of learning

Posted by jrbush82 on Wed, 05 Jan 2022 14:07:09 +0100

Cross domain

What is cross domain
The browser has a homology policy. When the 'protocol name', 'domain name' and 'port' of the url of the web page are the same, it is homology. One difference is cross domain
Homology strategy
The same origin policy restricts documents or scripts loaded from the same source, such as songs, from interacting with resources from another source This is a security mechanism for isolating potentially malicious files
Why do we need homology strategy
First, the front-end and server are deployed separately, and the interface request needs to cross domains. Second, we may load the pages of other websites as iframe embedded
What are the cross domain approaches
1.jsonp cross domain
2. Cross domain CORS
jsonp can only support get requests, and cors can support multiple requests cors is set up on the server side. cors does not need the front end to do any work
3. Proxy cross domain
nginx reverse proxy (operation or background)
webpack setting proxy cross domain (front end)
4.weksocket cross domain
5.postMessage
6. Cross domain in other ways
window.name+iframe
location.hash+iframe
document.domain
2.jsonp cross domain
Question 1: what do you say that jsonp is not real ajax?
1. The core of AJAX is to obtain the right and wrong contents of this page through xmlHttpRequest. The core of hsonp is to dynamically add the script tag and call the js script provided by the service server
2.jsonp only supports get requests, and ajax supports get and post requests
Question 2: what is the cross domain principle of jsonp

Although the browser has a homology policy, but

<script>
       //Cross domain using js
      function Data(data){
          console.log(data);
      }
   </script>
   <script src="http://huruqing.cn:3009/getData?callback=Data"></script>

How to create script dynamically
1. Create a method received by the user, such as getData
2. Dynamically insert script tags

 <script>
       //Cross domain using js
      function Data(data){
          console.log(data);
      }
      //Dynamically create script tags
      var script=document.createElement('script');
      script.src='http://huruqing.cn:3009/getData?callback=Data';
        document.body.appendChild(script);  
    </script>

Note: the jsonp interface is different from the ordinary interface and requires special processing on the server side

(4) Synchronous and asynchronous

Synchronization: you can only do one thing at a time. After you finish one thing, you can start to do the next thing

Asynchronous: doing many things at the same time

Advantages and disadvantages of synchronous and asynchronous
Advantages of synchronization: clear organization
Disadvantages: slow speed
Advantages of asynchrony: it can execute multiple at the same time with high efficiency
Disadvantages: it may make you in a hurry

2. Synchronization and asynchrony in JS

In js, synchronous operations are performed first and asynchronous operations are performed later

(5) A library that encapsulates ajax requests

jq.js encapsulates the method of requesting ajax

   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
      $.ajax({
          type : 'get',//Method of parameter transmission
          url : 'http://huruqing.cn:3009/getUserDetail ', / / corresponding interface address
          data:{
            userId : '92be12aba9b01f'//Parameters passed
          },
          dataType : 'json',//Data type of received parameter
          success : function(res){//After successful link
            console.log(res);
          },
          error : function(){//After link failure
              alert("connection failed");
          }
      })
    </script>

axios, a library that encapsulates only ajax requests, is currently the most popular

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js"></script>
 <script>
    //  get method
     axios.get('http://huruqing.cn:3009/getUserDetail',
     {params:{userId:'92be12aba9b01f'}}).then(function(res){
         console.log(res);
     }).catch(function(){
         alert('link failure');
     })
    //  post method
     axios.post('http://huruqing.cn:3009/getUserDetail',
     {userId : '92be12aba9b01f'}).then(function(ress){
         console.log(ress);
     }).catch(function(){
         alert('connection failed');
     })
 </script>

regular expression

What is a regular expression

Regular expression describes a pattern of string matching

Create regular expressions

1. Literal mode
2.new keyword
3. Regular parameters

 <script>
    // Literal method to create regular expressions
    var reg=/msg/g;
    //Create a regular expression through the new constructor
    var reg1=new RegExp('msg');
    // 3. Parameter i - case insensitive g - global matching m - multiline matching
 </script>

(2) Common matching rules

(1) Metacharacter
1. Any character
2.\w - letters, underscores, numbers
3.\s - any white space character
4. \d - number
5. \D - non numeric
6. | indicates or
7. ^ start of matching string
8. End of $matching string
9. [abc] means including any one of them

<script>

    //. represents any character
    var reg1=/./;
    console.log(reg1.test('123'));
     
    //\w stands for underline, letter and number
    var reg2=/\w/
    console.log(reg2.test('_1'));

    //\s represents a blank character
    var reg3=/\s/
    console.log(reg3.test(' '));

    //\d is a number
    var reg4=/\d/;
    console.log(reg4.test('4'));

    //\D means non numeric
    var reg5=/\D/
    console.log(reg5.test('_'));

    //|Indicates or
    var reg6=/4|5/
    console.log(reg6.test('4'));

    ///^/It starts with him
    var reg7=/^7/
    console.log(reg7.test('78'));

    //$means with him as the tail
    var reg8=/8$/
    console.log(re8.test(reg8));

    //[abc] can be a, b or c
    var reg9=/[abc]/
    console.log(reg9.test('a'));
 </script>

Antisense character

1. [^ x] matches all characters except 'x'
2... [^ xyz] same as above, matching any character except 'x,y,z'

Repeat matching

1.?— Zero or one repetition
2. + repeated one or more times
3. * repeated zero or more times
4. {n} repeated N times
5. {n,} repeated at least N times
6. {m,n} repeats m to N times, where m < n

/****** Repeat********/
//1. `?`  Zero or one repetition
var reg1 = /^https?:\/\//;   //  Indicates that it must start with http. s can appear 0 or 1 times
var str1 = "https://adfasdf";
console.log("boo1", reg1.test(str1));
var str1 = "http://adfasdf";
console.log("boo1", reg1.test(str1));

//2. ` + ` repeated one or more times
var reg2 = /a+/;  // Indicates that a must occur once or more
var str1 = "ssa";
var str2 = "ssaaa";
console.log("boo14", reg2.test(str1), reg2.test(str2));

//3. ` * ` repeated zero or more times
var reg3 = /a*/;
var str1 = "sss";
var str2 = "ssaaa";
console.log("boo3", reg3.test(str1), reg3.test(str2));

//4. {n} repeated N times
var reg4 = /^\d{4}-\d{2}-\d{2}$/;
var str = '2021-06-06';
console.log('boo4',reg4.test(str));

var reg4 = /\d{4}-\d\d?-\d\d?/;
var str = '2021-6-6';
console.log('boo4',reg4.test(str));

//5. {n,} repeated at least N times

//6. {m,n} repeat m to N times, where m < n
var reg6 = /a{2,4}/
var str = 'aabcd';
console.log('boo6',reg6.test(str));

Regular expression application

// 1. String replacement
var str = 'asdfasdfasdfwebasdfasdfasdfwebasdfasdfasdfweb'
// Replace web with Web Engineer
str.replace(/web/g,'web engineer');

// 2. Find the content that meets the regular conditions, for example: find all the pictures in the web page
var str = document.body.innerHTML;
str.match(/https?:\/\/.*?\.(png|jpeg|gif)/g);  

grouping

1. Group with brackets
2. Application of grouping

<script>
    // 1. Brackets indicate a whole
   

    // 2. Grouping
    

    // 3. String replacement grouping
	var str = '13812345678';
	var newStr = str.replace(/(\d{3})(\d{4})(\d{4})/,'$1****$3');
	console.log(newStr);
</script>

Greedy matching and lazy matching

1. The match method of string can check the match several times

 var str = 'asdfasdfasdfasdfasdf';
 var list = str.match(/a/g);
 console.log(list);

2. Greedy matching, as many matches as possible

 var str = document.body.innerHTML;
str.match(/https?:\/\/.*\.(png|jpeg|gif)/g); // Greedy matching, only one match can be obtained

3. Inert matching. There should be as few matches as possible, and then add? that will do

 var str = document.body.innerHTML;
str.match(/https?:\/\/.*?\.(png|jpeg|gif)/g); // Lazy matching, you can get multiple matches

Topics: Javascript Front-end Vue.js