This section describes how to implement token encryption

JWT (Json web token) : link: www.jianshu.com/p/576dbf44b… 1. Need a secret (random number, i.e. private key, can not be exposed, stay on the server side) 2. The back-end uses secret and encryption algorithms (such as HMAC-SHA256) to encrypt the payload(such as the account password) and generate a string (token). The token is returned to front-end 3. Token () 4 is added to each request header. The back end decrypts using the same algorithm

Header (base64) + Payload (base64) + Sign (Secrect +SHA256 signature, tamper-proof) The Authorization:’Bear ‘+ Token is added. How to tamper proof: Suppose the hacker tampered with our head or payload, because he didn’t have the private key Secrect, so he couldn’t get the correct signature. When he asked the server, the server also signed the header and payload, found that the signature was not the same as the signature, and rejected the request. The key is that the private key is on the server side.

The traditional cookie+session mode: the client must bring the cookie every time, and the cookie cannot cross domains. The server must store a session in memory every time. Cookies are easy to be hijacked, although they can be signed.

Why did Redux design reducer as a pure function

Redux is designed with no side effects and a traceable and predictable state of data changes.

How to design and implement seamless rotation

Simply put, the core of seamless rotation is to create a continuous effect. The easiest way to do this is to copy a rotatable element, and when the copied element is about to roll to the target location, the original element is put back into place to achieve a seamless rotatable effect.

Essence: With requestAmimationFrame(Callback), only one callback will be executed per 16.7ms to achieve a visual animation that does not drop frames.

useEffect(() => { const requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame const cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame const scrollNode = noticeContentEl.current const distance = scrollNode.clientWidth / 2 scrollNode.style.left = scrollNode.style.left || 0 window.__offset = Window. __offset | | 0 let requestId = null const scrollLeft = () = > {const speed = 0.5 window. __offset = window. __offset + speed scrollNode.style.left = -window.__offset + 'px' // When the distance is less than the offset, If (distance <= window.__offset) window.__offset = 0 requestId = requestAnimationFrame(scrollLeft)} requestId = requestAnimationFrame(scrollLeft) if (pause) cancelAnimationFrame(requestId) return () => cancelAnimationFrame(requestId) }, [notice, pause])Copy the code

The simulation implements a promise.finally

Promise the source code:

// New Promise((resolve,reject)=>{// setTimeout(resolve,1000) // setTimeout(reject,1000) //}).then(()=>{}) //. Catch (()=>{}) function Promise(execTutor) { Resolve,reject this.state = 'pedding' // Initialize state this.success = '' // Save the correct result this.error = '' // Save the wrong result This. fullFilledCallbacks = [] // save the correct callbacks this.rejectedCallbacks = [] // save the error callbacks // define resolve function resolve(value) {if (this.state == 'pedding') {// Prevent resolve, Reject this. State = 'fullfilled enclosing success = value enclosing fullFilledCallbacks. ForEach (fn = > fn ())}} / / reject function is defined Reject (value) {if (this.state == 'pedding') { Reject this. State = 'rejected' enclosing the error = value enclosing rejectedCallbacks. ForEach (fn = > fn ())}} / / definition then prototype method, Prototype. Then = function (onFullFilled, onRejected) {const Promise = new Promise((resolve, Reject) => {if (this.state == 'pedding') {if (this.state == 'pedding') { That no calls to resolve or reject this. FullFilledCallbacks. Push (() = > {try {let res = onFullFilled (enclosing success) / / execution results as the parameters of the next then resolve (res)} the catch (error) {reject (error)}}) enclosing rejectedCallbacks. Push (() = > {try {let res = onRejected(this.error) // Then = onRejected(this.error) Resolve (res)} catch (error) {reject(error)}})} else if (this.state == 'fullfilled') {try {let res = Resolve (res)} catch (error) {reject(error)}} else {try {let res = OnRejected (this.error) // Execute the result of the next then argument, Resolve (res)} catch (error) {reject(error)}}}) return promise Promise.prototype.catch = function (onRejected) { this.then(() => { }, Callback)} // Define a finally prototype method. Note that onFinished receives no arguments, and will execute onFinished regardless of success or failure before finally and pass the last result, Val, down Promise.prototype.finally = function(onFinished) { return this.then(val => { onFinished() return val }).catch((err) => { OnFinished () return err})} // define an all static method that passes a single argument, [promise,1,2]. Each item in the array can be a promise or a number. All = function (promises) {var arr = [] var num = 0; function precess(key, Arr [key] = value if (++num == callbacks.length) {resolve(arr)}} promises.forEach((item, I) => {if (item.then &&typeof item.then == 'function') {// If (item.then &&typeof item.then == 'function') {// If (item. Process (I, res)}). Catch (err){reject(err)}} else {process(I, item)}}); } // Run the race first, Race = function (promises) {promises. ForEach ((item, i) => { item.then(val=>resolve(val),err=>reject(err)) }); Exectutor (resolve, reject) // execute immediately and inject resolve,reject) // export module.exports = PromiseCopy the code

A.B.C.D or a[‘b’][‘c’][‘ D ‘], which is better?

A.B.C.D is faster than a[‘b’][‘c’][‘d’], which takes into account variables in [], and which is easier for the compiler to parse than the latter.

What is the realization idea of ES6 code into ES5 code

Babel is the standard configuration of ES6 to ES5. The general process of transformation is as follows:

1. Parsing: Parsing code strings to generate AST; (babel-loader: ts/jsx=>es6=>es5)

2. Conversion: Convert and modify AST according to certain rules; (Babel – core, Babel – polyfill, Babel – env)

3. Generation: Converts the modified AST into normal code.

Array programming problem

Generate a random array of integers of length 10, such as [2, 10, 3, 4, 5, 11, 10, 11,20], and arrange it into a new array, such as [[2, 3, 4, 5], [10, 11],[20]].

Function fromArray(arr){var map = new map () var sortedArr = array. from(new Set(arr)).sort((a,b)=>return A - b). / / to heavy and sorting sortedArr forEach (item = > {var key = math.h foor (item / 10)/groups/contains several 10 var group = map. Get (key) | | [] Group.push (item) map.set(key,group)}) return [...map.values()] //map.keys GetNumArr (length){//length indicates the quantity return array. from({length:length},()=>{return Var res = fromArray(getNumArr(10)) console.log(res) // is a two-dimensional arrayCopy the code

How to solve the 1px pixel problem of mobile Retina display

Retina display is also called Retina display, which is actually the name of a display technology. This technique compresses more pixels onto a single screen, resulting in a screen with surprisingly fine resolution. In fact, the word Retnia is closer to a marketing term than a technical ranking. Because in a sense, it’s a term apple coined to promote its products. Apple did file a patent on the term. While the resolution of a screen is usually expressed in “pixel x pixel” format, it’s the pixel density, known as PPI, that determines the sharpness of the screen, not the number of pixels. In addition to ppi, the distance between the eye and the screen also determines whether a screen is sharp enough to be called Retina. For a smartphone, 326 ppi is enough for a Retina display, 264 ppi for a tablet, and 220 ppi is enough for a laptop.

Transform scaleY(.5) 2.border-image 3.background-image 4.box-shadow

How to reverse the case of a string (for example, ‘AbC’ becomes’ AbC’).

function processString(str){ if(! str) return '' var arr = str.split('') var newArr = arr.map(item=>{ return item===item.toUpperCase()? item.toLowerCase():item.toUpperCase() }) return newArr.join('') }Copy the code

Introduce the principle of webpack hot update. How to update the page without refreshing the browser

1. Modify one or more files. 2. The file system receives the changes and notifies Webpack. 3. Webpack recompiles and builds one or more modules, and notifies THE HMR server for updates; 4.HMR Server uses webSocket to notify HMR Runtime that the JSONP needs to be updated, and HMR runtime requests to update JSONP through HTTP. 5. The HMR runtime replaces the updated modules, and if it is determined that these modules cannot be updated, triggers the entire page refresh.