“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Hello, everyone, I am Front-end LAN Feng, today I mainly share with you my notes 2021 front end test series: Fetch and AXIos, the method of communication between tabs in the browser, XSS and CSRF, and how to prevent them are often used in our work and often asked by interviewers. I hope the following article can help you.

The fetch and axios

Problem analysis

Fetch and Axios positioning understanding. Fetch is the browser-provided API, and AXIos is a component packaged by the community.

Fetch is a low-level API that you can think of as native XHR, so it’s not as comfortable to use and needs to be wrapped. For years, XMLHttpRequest has been a close aide to Web developers. Whether directly or indirectly, when we talk about Ajax technology, we usually mean XMLHttprequest-based Ajax, which is a technology that can effectively improve page communication. The rise of Ajax was inspired by Google’s Gmail, and has since been widely used in many Web products (applications). It is safe to assume that developers have adopted XMLHttpRequest by default as the basis for current Web applications to communicate with remote resources. This article will introduce the latest alternative to XMLHttpRequest, the Fetch API, which is an official W3C standard. The Fetch API will be introduced below, and the scenarios it can be used in and the problems it can solve.

1. Fetch Advantages:

  1. Syntax concise, more semantic
  2. Support async/await based on standard Promise implementation
  3. More low-level, rich API (request, response)
  4. XHR is a new implementation in the ES specification

Fetch is a low-level API that you can think of as native XHR, so it’s not comfortable to use and needs to be wrapped.

  1. The FETCH only reports an error to the network request, and considers 400,500 as a successful request. The server does not reject the 400,500 error code. The FETCH is rejected only when the request cannot be completed due to network errors.
  2. Fetch (URL, {credentials: ‘include’})
  3. Fetch does not support abort and timeout control. The timeout control implemented by setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in waste of traffic
  4. Fetch has no way of natively monitoring the progress of requests, whereas XHR does
fetch('http://example.com/movies.json')   // The second argument specifies post GET
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
Copy the code

Axios is an HTTP client based on Promise for browsers and NodeJS. It is essentially a wrapper around native XHR, but it is an implementation version of Promise that complies with the latest ES specification and has the following characteristics:

  1. Create an XMLHttpRequest from the browser
  2. Supporting Promise API
  3. Client support prevents CSRF
  4. Provides some interfaces for concurrent requests (important, much easier to do)
  5. Create HTTP requests from Node.js
  6. Intercept requests and responses
  7. Transform request and response data
  8. Cancel the request
  9. Automatically convert JSON data
/ / axios, for example
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code

Bottom line: Axios provides concurrent encapsulation without the problems of FETCH, and is small enough to be the preferred method of request.

The interview questions point

  1. Fetch is natively supported by browsers that standardize the underlying API
  2. Axios is a wrapped framework
  3. The pros and cons of FETCH and Axios

Answer the train of thought

First, what are fetch and Axios? The pros and cons of FETCH and Axios are then explained

Relevant extension

  1. Axios’ Github repository address
  2. Axios API documentation
  3. Fetch’s API specification MDN community notes
  4. The w3c and whatwg

Communication between multiple tabs in a browser

Problem analysis

This topic focuses on the technology of data interaction between tabs in multi-page applications. Multi-page communication can be realized by using browser data storage and server. Browser data storage is mainly local storage. That is, localStorage methods such as localStorage and Cookie are invoked. Server mode mainly uses Websocket technology to make multiple tabs monitor server push events to obtain data sent by other pages.

Browser storage:

1. Call localStorage

Add (modify, delete) content in a TAB using localstorage.setitem (key,value); Listen for storage events in another TAB. You can obtain the value stored in localStorge to communicate between different tabs.

Localstorage.setitem (name,val) on a TAB to save data Localstorage.removeItem (name) raises the ‘storage’ event when data is removed. In another TAB, listen for the Storage event of the Document object and get information from the event object property

Event The event object contains the following information

  1. domain
  2. newValue
  3. oldValue
  4. key

TAB Page 1:

<input id="name"> 
<input type="button" id="btn" value="Submit"> 
<script type="text/javascript"> 
        window.onload = function () {
            var btnEle = document.getElementById('btn');
            var nameEle = document.getElementById('name');
            btnEle.onclick = function () {
                var name = nameEle.value;
                localStorage.setItem("name", name); }}</script>
Copy the code

TAB Page 2:

<script type="text/javascript"> 
        window.onload = function () {
            window.addEventListener("storage".function (event) {
                console.log(event.key + "=" + event.newValue);
            });
        }
</script>
Copy the code

2. Call the cookie + setInterval ()

The information to be transmitted is stored in the cookie, and the cookie information can be read at certain intervals to obtain the information to be transmitted at any time.

Store the message to be delivered in cookies on page A

Set setInterval on page B to read the value of cookie at a certain interval.

Page 1:

<input id="name"> 
<input type="button" id="btn" value="Submit"> 
<script type="text/javascript"> 
$(function(){$("#btn").click(function(){ 
var name=$("#name").val(); 
document.cookie="name="+name; 
}); 
}); 
</script>
Copy the code

Page 2:

<script type="text/javascript"> 
$(function(){ 
function getCookie(key) { 
return JSON.parse("{\" " + document.cookie.replace(/; \s+/gim."\ \", "").replace(/=/gim."\", \ "") + "\"}")[key]; 
} 
setInterval(function(){ 
console.log("name=" + getCookie("name")); 
}, 10000); 
}); 
</script>
Copy the code

3. Listen for server events

  1. ** WebSocket communication **

WebSocket is full-duplex communication and can naturally realize communication between multiple tabs. WebSocket is a new HTML5 protocol that aims to create an unrestricted two-way communication channel between the browser and the server, for example, so that the server can send a message to the browser at any time. Why can’t the traditional HTTP protocol do what WebSocket does? This is because HTTP is a request-response protocol. The request must be sent from the browser to the server before the server can respond to the request and then send the data to the browser. Others say that HTTP can be implemented using polling or Comet. The disadvantages of this mechanism are that first, it is not real-time enough, and second, frequent requests will put great pressure on the server. Comet is also polling by nature, but in the absence of a message, the server waits for a message and then responds. This mechanism solves the real-time problem for the time being, but it introduces a new problem: a server running in multithreaded mode leaves most threads hanging most of the time, wasting server resources. In addition, any gateway on an HTTP connection can close the connection if there is no data transfer over a long period of time, and gateways are out of our control, requiring Comet connections to send periodic pings to indicate that the connection is “working.” WebSocket is not a new protocol, but uses HTTP to establish connections. Why can WebSocket connections achieve full-duplex communication but NOT HTTP connections? In fact, HTTP is based on TCP, which implements full-duplex communication. However, the request-reply mechanism of HTTP limits full-duplex communication. After the WebSocket connection is set up, it simply states: Let’s communicate without using HTTP and send data directly to each other. The secure WebSocket connection mechanism is similar to HTTPS. First, when a browser creates a WebSocket connection using WSS :// XXX, it creates a secure connection using HTTPS. Then, the HTTPS connection is upgraded to a WebSocket connection, and the underlying communication is still using the secure SSL/TLS protocol.

WebSocket connections must be initiated by the browser. Features:

(1) Based on THE TCP protocol, the implementation of the server side is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.

(3) The data format is relatively light, the performance overhead is small, and the communication is efficient.

(4) Can send text, can also send binary data.

(5) There is no source restriction, and the client can communicate with any server.

(6) The protocol identifier is WS (if encrypted, WSS), and the server URL is the URL.

Example: browser-side code

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open'.function (event) {
    socket.send('Hello Server! ');
});

// Listen for messages
socket.addEventListener('message'.function (event) {
    console.log('Message from server ', event.data);
});
Copy the code

** 2. New feature of HTML5 browser SharedWorker**

A normal webworker can be created directly using new Worker(), which is proprietary to the current page. Then there is the sharing worker(SharedWorker), which can be used by multiple tabs and iframes. SharedWorker can be used by multiple Windows, but the tabs must be of the same origin (same protocol, host and port number).

Create a new js file, worker.js, with the following code:

// sharedWorker can use js files directly to the server instead of packing them into the project
let data = ' ';
let onconnect = function (e) {
  let port = e.ports[0];
  port.onmessage = function (e) {
    if (e.data === 'get') {
      port.postMessage(data)
    } else {
      data = e.data
    }
  }
}
Copy the code

The code on the Webworker side (let’s call it that) is like this: simply register an onMessage event that will be triggered when the client (using the sharedWorker’s TAB) sends a message.

Note that webworker cannot be used locally, due to the security mechanism of the browser itself, so my example is also placed on the server, worker.js and index.html are in the same directory.

Because the communication between the client and webworker is not full-duplex like that of websocket, the client sends and receives data in two steps. There will be two buttons in the example, corresponding to a request to send data to the sharedWorker and a request to get data, but they are essentially the same event — send a message.

The Webworker will make a judgment. When the data passed is “get”, it will send the value of the variable data back to the client. In other cases, it will store the data passed by the client into the data variable. Here is the client code:

// This code is required to open the page and register the SharedWorker, indicating that the worker.port.start() method is specified to establish a connection with the worker
    if (typeof Worker === "undefined") {
      alert('Current browser does not support Webworkers')}else {
      let worker = new SharedWorker('worker.js')
      worker.port.addEventListener('message'.(e) = > {
        console.log('Data from worker:', e.data);
      }, false);
  
      worker.port.start();
      window.worker = worker;
    }
// The postMessage method is used to fetch and send messages. The convention here is to pass 'get' to fetch data.
window.worker.port.postMessage('get')
window.worker.port.postMessage('Send message to worker') Page A sends data to the worker, and then opens page B to callwindow.worker.port.postMessage('get'), can receive the data sent to the worker by page A.Copy the code

The interview questions point

What is a multi-page application

Two browser storage methods to achieve multi-tab communication

Websocket and Shareworker implement multi-page communication

Answer the train of thought

Firstly, the application scenario of multi-page application is clarified, and then the key technologies of multi-page communication by browser and server are introduced respectively.

Relevant extension

  1. H5 multithreading (Worker SharedWorker) use details
  2. SharedWorker api
  3. websocket

XSS, CSRF, and how to prevent it

Problem analysis

In the field of Web security, XSS and CSRF are the most common attacks. Let’s start with a brief overview of what XSS and CSRF are.

XSS stands for Cross Site Script.

Originally abbreviated as CSS, it is called XSS in the security world to distinguish it from Cascading Style Sheets.

XSS attack refers to an attack in which an attacker injects malicious client code into a website and tampers the client’s web page through malicious scripts, so as to control the user’s browser or obtain the user’s private data when browsing the web page.

Malicious scripts that attackers inject into client web pages usually include JavaScript, but sometimes also HTML and Flash. There are many ways to carry out XSS attacks, but they all have in common: sending private data such as cookies and sessions to the attacker, redirecting the victim to a website controlled by the attacker, and performing malicious operations on the victim’s machine.

XSS attacks can be divided into three categories: reflective (non-persistent), storage (persistent), and DOM based.

XSS type

1. Reflected XSS code appears in THE URL when making a request and is submitted to the server as input. The server parses and responds, and the XSS code is returned to the browser with the response content. This process is like a reflection, so it’s called reflective XSS.

2. The difference between Stored XSS and Reflected XSS lies in that the offensive scripts are Stored on the server side (database, memory, file system) and can be completely obtained and executed by ordinary users from the service, thus acquiring the ability to spread on the network.

3. DOM type (DOM-based or local XSS) refers to DOM or local XSS attack: in fact, it is a special type of reflective XSS, which is a vulnerability based on DOM document object model. Page content can be modified dynamically through the DOM, fetching data from the DOM from the client and performing it locally. Based on this feature, you can use JS scripts to exploit XSS vulnerabilities.

Examples of real-world attacks:

  1. For example, there is a website that lets you enter a comment on an article:

Defense measures:

(1) Input filtering. One of the methods to avoid XSS is to filter the content entered by users. Reliable input validation for all user-submitted content, including URL, query keywords, POST data, etc., only accept content submitted within the specified length range, in appropriate format, using the expected characters, and filter the rest. (Both client and server)

(2) Output escape

For example, when inserting untrusted data between HTML tags, the first thing to do is to create an HTML Entity encoding HTML character Entity for the untrusted data

function htmlEncodeByRegExp  (str){  
         var s = "";
         if(str.length == 0) return "";
         s = str.replace(/&/g."&amp;");
         s = s.replace(/</g."&lt;");
         s = s.replace(/>/g."&gt;");
         s = s.replace(/ /g."&nbsp;");
         s = s.replace(/\'/g."& # 39;");
         s = s.replace(/\"/g."&quot;");
         return s;  
 }
var tmpStr="<p>123</p>";   
var html=htmlEncodeByRegExp (tmpStr)
console.log(html) //< p> 123< /p>
document.querySelector(".content").innerHTML=html; //<p>123</p>
Copy the code

(3) Use HttpOnly cookies

Mark important cookies as HttpOnly, so that when the browser makes a request to the Web server, the cookie field is attached, but the cookie cannot be accessed in the JS script. This avoids XSS attacks that use JavaScript document.cookie to get cookies.

Modern Web development frameworks such as vue.js and React. Js have been designed with XSS attacks in mind to further abstract, filter and escape HTML interpolation. We can avoid XSS attacks in most cases if we use them skillfully and correctly.

CSRF stands for cross-site request forgery. CSRF, as its name implies, is a bogus request that impersonates the normal operation of the user in the site. As we know, the vast majority of websites identify user identities through cookies (including those that use server-side Session, because Session IDS are mostly stored in cookies) and then grant authorization. Therefore, to forge the normal operation of the user, the best way is through XSS or link spoofing and other ways, so that the user in the local machine (that is, the browser with identity cookie) to initiate the user does not know the request.

You can understand it this way: the attacker steal your identity, in the name of your sending malicious request, the request for server is perfectly legal, but finished the attacker’s expectation of an operation, such as in the name of your email, send messages, to steal your account, add a system administrator, or even to buy goods, virtual currency transfer, etc. Web A is A website with CSRF vulnerability, Web B is A malicious website constructed by an attacker, and User C is A legitimate User of Web A.

CSRF attack The attack mechanism and process are as follows:

  1. User C opens the browser, accesses trusted website A, and enters the user name and password to request to log in to website A.
  2. After the user information is verified, website A generates Cookie information and returns it to the browser. At this time, the user successfully logs in to website A and can send requests to website A normally.
  3. Before exiting website A, the user opens A TAB page in the same browser to visit website B.
  4. After receiving the user’s request, website B returns some offensive code and sends A request to visit third-party site A.
  5. After receiving these offensive codes, the browser, according to the request of website B, carries the Cookie information without the user’s knowledge and sends A request to Website A. Website A does not know that the request is actually initiated by B, so it will process the request with C’s permission according to the Cookie information of user C, resulting in the malicious code from Website B being executed.

For example:

The victim, Bob, had a deposit with the bank and sent a request to the bank’s website

http://bank.example/withdraw?account=bob&amount=1000000&for=bob2

Bob can transfer 1,000,000 deposits to boB2 account. Typically, after the request is sent to the site, the server first verifies that the request came from a valid session and that the session’s user Bob has logged in successfully.

Mallory himself had an account at the bank and knew that the URL could transfer money. Mallory can send a request to the bank himself:

http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory.

But the request comes from Mallory, not Bob, who cannot pass security authentication, so the request will not work.

At this time, Mallory thought of using CSRF attack method, he first made a website, put the following code in the website:

SRC = “http://bank.example/withdraw? Account = Bob&amount =1000000&for=Mallory “, and entice Bob to visit his website by advertising etc. When Bob visits the site, the above URL is sent from Bob’s browser to the bank, and the request is sent to the bank server with a cookie from Bob’s browser. In most cases, the request fails because it asks for Bob’s authentication information. However, if Bob happens to visit his bank shortly after that, his browser’s session with the bank’s web site has not expired, and the browser’s cookie contains Bob’s authentication information. The url request will be answered, and the money will be transferred from Bob’s account to Mallory’s, without Bob knowing it. When Bob later found that the money was missing, even if he checked the bank logs, he could only find that there was indeed a legitimate request from him to transfer the money, without any trace of attack. Mallory gets the money and gets away with it.

Prevent CSRF

(1) Verify the HTTP Referer field and use the Referer in the HTTP header to determine whether the source of the request is legitimate. The Referer records the source address of the HTTP request.Copy the code

Advantages: Easy to implement, just add an interceptor at the end to check the Referer value for all security-sensitive requests. Especially for the current existing system, there is no need to change any existing code and logic of the current system, no risk, very convenient.

Disadvantages: The Referer value is provided by the browser and cannot be trusted completely. There is a risk of forgery in the Referer in earlier versions of the browser. Users themselves can set their browsers to stop providing Referer when they send requests, and the site will deny access to legitimate users.

(2) Add token to request address and verify. The reason why CSRF attack can be successful is that the hacker can completely forge the user’s request, and all the user authentication information in the request is in the cookie, so the hacker can directly use the user’s own cookie to pass the security authentication without knowing the authentication information. The key to defending against CSRF is to put information in the request that a hacker cannot forge and that does not exist in a cookie. A randomly generated token can be added to the HTTP request as a parameter, and an interceptor can be established on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be rejected as a CSRF attack.

Advantages: This method is safer than checking the Referer. Tokens can be generated after the user logs in and placed in the session. Tokens can then be taken out of the session on each request and compared with the tokens in the request.

Disadvantages: It is difficult to add tokens to all requests. It is difficult to guarantee the security of the token itself, and the token can still be used to obtain the token.

This method also uses tokens and validates them. Unlike the previous method, tokens are not placed as parameters in the HTTP request. Instead, they are placed in custom attributes in the HTTP header. With the XMLHttpRequest class, you can add the CSRFToken HTTP header attribute and put the token value into all of the class requests at once. This eliminates the inconvenience of adding the token to the request in the previous method, and the XMLHttpRequest address is not logged in the browser’s address bar, and the token is not leaked to other sites through the Referer.

Advantages: Unified management of token input and output ensures token security.

Disadvantages: Limited and cannot be implemented on non-asynchronous requests.

The interview questions point

What exactly are XSS and CSRF

Identify the characteristics of XSS and CSRF attacks

How do I defend against XSS and CSRF attacks

Answer the train of thought

First of all, XSS (Cross Site Scripting) is a cross-site request forgery (CSRF). Then, two examples of these attacks are given respectively. Finally, the prevention measures of these two attacks are discussed.

Relevant extension

  1. Brief introduction of XSS and CSRF and preventive measures
  2. The server is attacked by DDoS

Concern public number: programmer Shi Lei gets more front end test questions