background
As a graduation nearly two years but the front is still a rookie Lv1 grade, was supposed to be doing his bit in the former company dedicated to live, but companies with affected by outbreaks repeatedly cut to deduct my salary is not much, so I resolutely decided to jobs in the “cold” early spring on tour, after 10 to 20 days or so, I ended the battle with a good result. Here is a summary of the knowledge covered by the interview questions I met this time, hoping to bring you some small help. If there is anything wrong in the article, you are welcome to point out.
css
1. Talk about the properties and differences of box-sizing
- Content-box: The calculated width and height does not include the border and padding of the content.
- Border-box: Width and height attributes include content, padding, and borders, but not margins.
2. Visibility: hidden, display: none
- DOM structure: the former will be rendered and just hidden, taking up space; The latter is not rendered and does not take up space;
- Performance: changing the former will cause redraw, high performance; Changing the latter will cause reflux and poor performance;
- Inheritance: the former will inherit the quilt element, and the child element can be used by setting visibility: visible; To unhide; The latter does not inherit from the quilt element, and the subclasses cannot be shown;
- Opacity: 0, visibility: hidden, display: none and their application scenarios are compared
3. How do I center a div horizontally and vertically
- Elastic layout
- Translate
- Absolute positioning + margin
- More ways
4. Describe the elastic layout and its common properties
- Refer to this article, CSS3 elastic box layout
5. Do you know BFC? What does it do
-
A BFC is a block-level format context, which acts as an isolated container that does not interact with external elements.
-
role
- Remove the floating
- Prevent margins from collapsing under the same BFC
-
The trigger condition
- Body root element
- Float float
- Absolute positioning
- Display for elastic layout and table layout
- Overflow visiable
js
1. Differences between Typeof and Instanceof
- Typeof: determines the typeof the value.
- Intanceof: Checks whether the constructor’s prototype is on the object’s prototype chain;
2. Determine the type of a value
- The typeof + intanceof;
- Object.prototype.toString.call
3. What is the difference between anti-shake and throttling? How do you do that?
- Buffeting: The corresponding function is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the time will be recalculated.
function debounce(fn, time) {
lettimer = null; // Timer IDreturn function() { clearTimeout(timer); // Clear the previous timer when the event is triggeredsetTimeout(() => {// Create a new timer that only executes fn.apply(this, arguments) after a certain amount of time; }, time); }}Copy the code
- Throttling: After the event is triggered, it checks whether the function has been executed within n seconds. If it has not been executed, it will execute.
function throttle(fn, time) {
let isRun = false; // A variable that defines whether a function was executed within the current eventreturn function () {
if (isRun) return; // If the function is executed at the current time, it will be directreturn
isRun = true; // If not executed, set it totrue
setTimeout(() => {// Create a timer to execute the function after n seconds and assign isRun tofalse
fn.apply(this, arguments);
isRun = false; }, time); }}Copy the code
4. What is the difference between a deep copy and a shallow copy? Can you implement a deep copy?
- Shallow copy copies only the first layer of an object. If the property of an object is a reference type, only the reference address is copied. When the value is changed, all references are changed. Deep copy resolves the problem of shallow copy.
// The function copy is not consideredfunction deepClone(obj) {
if(obj === null || typeof obj ! = ='object') return obj;
const constructor = obj.constructor;
let cloneObj;
switch (constructor) {
case Boolean:
case Date:
case Number:
case String:
case RegExp:
return new constructor(obj);
default:
cloneObj = new constructor(); } // This method returns all attributes of the target value (including symbol) reflect.ownkeys (obj).foreach (key => {cloneObj[key] = deepClone(obj[key])
})
return cloneObj;
}
Copy the code
5. Can you realize the difference between call and apply?
- The call method accepts a list of parameters, while the Apply method accepts an array or an array of classes.
Function.prototype._call = function(thisArg, ... arg) { thisArg = thisArg || window || global; ThisArg. ThisFn = this; thisArg. ThisFn = this; thisArg. Const result = thisarg.thisfn (... arg); delete thisArg.thisFn;return result;
}
Function.prototype._apply = function(thisArg, argsArray) { thisArg = thisArg || window || global; ThisArg automatically points to the global object when null or undefined; thisArg.thisFn = this; // Bind the execution scope to the function that needs to be executedlet result;
if(argsArray = = = null | | argsArray = = = undefined) {/ / argsArray value is null or undefined, Thisarg.thisfn (); thisarg.thisfn (); }else if (typeof argsArray === 'object') { result = thisArg.thisFn(... argsArray); } delete thisArg.thisFn;return result;
}
Copy the code
6. Talk about prototypes and prototype chains
- Prototype: Every object in JS has a __proto__ attribute, called an implicit prototype, that points to the prototype of that object’s constructor, which is called the display prototype, or prototype object.
- The prototype chain: When we call a method or property on an object, the object is first looked up in its current scope. If it is not found, the object is looked up in its prototype constructor based on __proto__. The constructor’s prototype constructor looks for its prototype constructor’s __proto__ attribute… Null (end point), which returns the corresponding method or attribute if it is found, and returns an error or undefined if it is not found. This search process is called prototype chain.
7. What are the common inheritance methods in ES5?
-
Prototype chain inheritance: directly assign the prototype of a subclass to an instance of the Parent class, i.e. child.prototype = new Parent();
-
disadvantages
- Because the implicit archetypes of all subclass instances point to Child.prototype, the same parent instance, reference type attributes on the parent instance are shared
- You cannot pass arguments to the superclass constructor when creating a subclass instance
-
-
Borrowing constructor inheritance: Binding the execution scope of the parent constructor to the subclass constructor by call or apply solves two problems in stereotype chain inheritance.
- disadvantages
- Methods and properties on the superclass constructor prototype are not accessible by subclass instances
- disadvantages
. Function Child() {// Parent Parent. Call (this); }...Copy the code
- Combination of inheritance: The combination of prototype chain inheritance and constructor inheritance gives full play to the advantages of both, that is, using prototype chain to achieve inheritance of prototype attributes and methods, and using constructor inheritance to achieve inheritance of instance attributes.
- disadvantages
- The Parent constructor is called twice each time a subclass instance is created, so that child.prototype generates the name property twice, and the latter overrides the former, which does not affect inheritance but is not very elegant.
- disadvantages
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function () {
return this.name;
}
functionChild(name, age) {// Inherits the attribute parent.call (this, name); // Call Parent() this.age = age; } // Create a new Parent(); / / the first call to the Parent () the Child. The prototype. The constructor = Child; // Make its constructor point to itselfCopy the code
- Parasitic combinatorial inheritance: When we want to inherit method properties from the Parent prototype, instead of calling the Parent constructor for the child’s prototype, we simply create an object that implicitly points to the Parent constructor prototype, newobj.__proto__ = Parent. Prototype, then, The object.create () method is just fine.
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function () {
return this.name;
}
functionChild(name, age) {// Inherits the attribute parent.call (this, name); this.age = age; } Child.prototype = Object.create(Parent.prototype); / / create the Child through the create method. The prototype. The constructor = Child; // Make its constructor point to itselfCopy the code
Reference article: JavaScript Advanced Programming (3rd edition)
Implement a new function
function _new(Fn,... Arg) {// Must be a function and cannot be an arrow function if(typeof Fn! == "function" || ! Fn.prototype) throw Error(`Fn is not a constructor`); // Assign the new Object's implicit prototype to the constructor's prototype, obj.__proto__ = Fn. Prototype const obj = object.create (Fn. Prototype); Const isRet = fn. call(obj,... arg); Return isRet instanceof object? isRet : obj; }Copy the code
9. What is the difference between arrow functions and ordinary functions?
- If there is no this, this inherits from the previous level, so call, apply and bind cannot be used to bind this
- Arguments have no arguments objects of their own, and look up through the scope chain
- Cannot be used as a Generator function.
- There is no prototype attribute, so you can’t call it with the new keyword
Make a promise come true
I was implementing a very low match promise, the code is not posted, recommend Kun Kun big guy promise implementation
11. What is the difference between promise, async/await, and setTimeout?
First, the JS event loop is divided into macro tasks and micro tasks, and the current execution stack execution order is synchronous code -> code in micro tasks -> code in macro tasks.
- Promise: The promise function itself is executed synchronously, only its then or catch methods are executed asynchronously, and its callbacks are placed on the microtask queue in the event loop, allowing the synchronized code to execute first.
- Async/await: When an async keyword is added to a function, it indicates that there may be an asynchronous method in the current function. The await keyword can only be used in an async function followed by an expression. When an async function meets the await keyword, the following expression will be executed synchronously and the code following the expression will be put into the microtask queue. Let the synchronized code execute first.
- SetTimeout /setInterval: The callback function in the timer will be placed in the macro task queue and executed after the code in the synchronous and microtask queues finishes executing
The browser
1. What is the rendering process of the browser?
The main process is:
- The browser parses the HTML to generate a DOM tree
- The browser parses the CSS to generate the CSSOM tree
- Merge the DOM tree and the CSSOM tree to generate the render tree
- According to the layout of the rendering tree, the location size information of each node is calculated
- Finally, draw each node to the page and refer to the ten-minute browser rendering process
2. What is the difference between redraw and reflow?
- Redraw: node properties or style changes do not affect the layout, such as color,background-color,visibility, performance is relatively good
- Return: change layout or geometric properties, such as display: none, width, height, and poor performance
- Detailed visible
3. Browser caching mechanism
For an in-depth understanding of the browser caching mechanism, this article covers browser caching in great detail.
React
1. React Add a key to a list.
- Improve the efficiency of diff peer comparisons, because only by adding a unique index to the looping list can you compare who changed directly after the update, otherwise you can only compare one by one
2. What do you think are the advantages of the virtual DOM?
- Answer here directly labeled especially big www.zhihu.com/question/31…
3. When is setState asynchronous and synchronous?
- React is asynchronous in its synthesized events and life cycle, and synchronous in its native events and timers. This “asynchrony” is not implemented by asynchronous code, but by synchronous code, which combines multiple states for batch updates. The reasons for this are as follows
4. React What are the communication modes?
- Parent component communication: The parent component passes values to the child component through the props property
- Parent component communication: The child component passes values as arguments to the parent component through functions of the child component
- Sibling communication: Find the common parent of both components and pass values in combination with the previous two methods
- Cross-hierarchy component communication: Context, the basic usage is as followsTo see details
// Create context. / SRC /context.js import {createContext} from"react"Const {Provider, Consumer} = createContext(const {Provider, Consumer} = createContext("Default value") export{Provider, Consumer} // Use Provider to wrap components in common ancestor components that need context values./ SRC/app.js import {Provider} from"./context" import Child from "./child" function App() { return ( <Provider value={"Values to be passed"}> <Child /> </Provider> ); } // Grandson./ SRC /child.js import Grandson from"./Grandson" function Child() { returnGrandson import {Consumer} from the Provider, what is the value that needs to be passed"./context" function Grandson() { return ( <Consumer> {value => <div>{value}</div>} </Consumer> ) } Copy the code
- State management library communication: Use third-party state management libraries such as Redux or Mobx to communicate
5. What life cycles do react execute during mount, update, and uninstall phases?
-
Constructor -> static getDerivedStateFromProps(UNSAFE_componentWillMount) -> Render -> componentDidMount
-
Update phase: The static getDerivedStateFromProps (replacement UNSAFE_componentWillReceiveProps) – > shouldComponentUpdate – > UNSAFE_componentWillUpdate (Not recommended, This will not be called if static getDerivedStateFromProps or getSnapshotBeforeUpdate is used) -> render -> getSnapshotBeforeUpdate -> componentDidUpdate
-
Unloading stage: componentWillUnmount
Detailed usage
6. What do you know about React optimizations?
- ShouldComponentUpdate: Add this life cycle to the class component to return a Boolean to determine whether to update the component, true for update, false for not update. This function is implemented by default in PureComponent in a shallow comparison of prop and state
- Memo: This applies only to function components. By default, like PureComponent, only shallow comparisons are made, but you can use the pass function as the second argument to implement specific update logic. Note that the pass function returns a Boolean update as opposed to shouldComponentUpdate, which is true. False to update
- UseMemo: This function is an API in React Hook. It can remember a value. When using a scenario that requires a lot of calculation, the value can be remembered to avoid calculation every time
Const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); // Const memoizedFn = useMemo(() => fn, deps)Copy the code
- Dynamically load components: Use react. lazy in conjunction with react. Suspense to load components dynamically and gracefully degrade usage methods during loading
- Avoid using anonymous functions: When passing functions to a child component, if you use an anonymous function to return a pass function, the anonymous function will be regenerated every time the parent component re-renders, which may result in additional re-rendering of the component
- Fragment: When a component needs to return more than one element, it is common to wrap a div in the outermost layer. When that div is useless, you can use the Fragment to wrap it without adding additional nodes to the DOM.
7. React how to reuse logic
-
HOC: a function that takes a component as an argument and returns a new component
- Implementation method
- Property broker: That is, add props to the incoming component
// A simple examplefunction HOC(WrappedComponent) { return class newComponent extends React.Component { render() { const newProps = { username: "beadre"}; // this. Props is the props received by HOCreturn<WrappedComponent {... this.props} {... newProps} /> } } }Copy the code
- Reverse inheritance: Returns a class that inherits from the component passed in
// A simple examplefunction HOC(WrappedComponent) { return class newComponent extends WrappedComponent { render() {// Use this to access the WrappedComponent's state, props, component lifecycle methods, and render methods.return super.render() } } } Copy the code
- Property broker: That is, add props to the incoming component
- disadvantages
- It is not intuitive to see which props were passed in the returned component
- If the name of the props passed is the same as that of the original props, the original properties will be overwritten
See the React component Reuse guide
- Implementation method
-
Render props: A simple technique for sharing code between React components using a prop prop with a value of function
// A simple example import React from"react" class RenderProps extends React.Component { state = { count: 0 } render() { return ( <div onClick={() => this.setState({count: this.state.count + 1})}> {this.props.render(this.state.count)} </div> ) } } function App() { return<RenderProps render={count => <h1> </h1>}Copy the code
- Features: Render props avoids all the disadvantages of HOC, but is a bit more cumbersome to reuse than HOC
See the React component Reuse guide
-
Customize the hook
- disadvantages
8. Suppose one widget on the page goes wrong for some reason, how can it not affect the other components?
- Error Boundaries
9. How do YOU change data in Redux?
- The user performs an operation on the view, triggers an event and issues an action to the Store via the Dispatch method (if the request is asynchronous, the action will be issued to the middleware)
- When the middleware receives the action, it performs the corresponding asynchronous request and sends an action to reducer after receiving the returned data (this step is only performed if middleware exists).
- Upon receipt, the Store sends the current state and received actions to the reducer using parameters
- Reducer performs the appropriate actions based on the action and returns a new state to the store
- Because the React component received the props(state) change, it will trigger the component to rerender.
10. You mentioned React-redux
The react-redux implementation uses the React Context API to pass the store in the redux to the value property of the Provider in the context, and then fetch it from the consumer in the descendant component.
There are two commonly used apis:
-
Provider: Enables connect methods at the component level to retrieve stores. This is usually used to wrap the root component (the common parent of the component that wants to retrieve stores) with a store property that receives Redux’s Store
-
Connect: Is a HOC that connects the React component to the Redux store and can accept four parameters
- MapStateToProps: a function that takes two arguments (state, ownProps) and returns an object to merge with the component’s props. If this parameter is defined, the component will listen for changes in the Redux store
- MapDispatchToProps: is a function or object used in the description of Action Creator. If this parameter is passed, the component will not receive dispatch
- MergeProps: a function that receives the results of the execution of mapStateToProps and mapDispatchToProps and the props of the component itself, and returns an object to merge with the props of the component
- Options: an object that can customize the behavior of the Connector
More detailed API and usage
webpack
1. Common Loaders and their functions
babel-loader
: Convert older JS versions to ES5file-loader
: Outputs the file to the folder and returns the (relative) URLurl-loader
: Is similar to file-loader, except that it can limit the size of files to be processed. If the size is smaller than the limit, base64 is directly returnedcss-loader
After parsing the CSS file, load it with import and return the CSS codestyle-loader
: Inject CSS into the style tagpostcss-loader
: Automatically adds the browser prefix of the CSS3 attributeless-loader
: Parses less files into CSS filessass-loader
: Parses SCSS files into CSS filests-loader
: Parses ts files into JS fileseslint-loader
: Uses ESLint to check JS codevue-loader
: Load and translate Vue componentscache-loader
: Caches the parsed result of the Loader to disks
More loader
2. Common plugins and their functions
html-webpack-plugin
: Simply create an HTML file for server accessclean-webpack-plugin
: Clear foldersignore-plugin
: Ignores some files in the module packageterser-webpack-plugin
: Compresses JS codeHotModuleReplacementPlugin
: Enables module hot replacementDllPlugin
: split bundles
More the plugin
3. Difference between Loader and plugin
- Loader: a function that preprocesses and transforms the received files. Webpack can only process javascript, so use loader first
- Plugin: Enriches webpack functions. It does not operate files directly, but works based on the event mechanism. It listens to some nodes in the Webpack process and performs a wide range of tasks
4. How to package multi-page apps
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
page1: './src/page1.js',
page2: './src/page2.js'} / /... plugins: [ new HtmlWebpackPlugin({ template:'./public/page1.html',
filename: 'page1.html'// if there are multiple html-webpack-plugin, filename must be specified, otherwise, index.html chunks: ['page1'}), new HtmlWebpackPlugin({template:});'./public/page2.html',
filename: 'page2.html'// if there are multiple html-webpack-plugin, filename must be specified, otherwise, index.html // chunks: ['page2'] will import all js files by default}),]}Copy the code
5. Webpack hot update principle
- First, webpack-dev-server (WDS) establishes a long webSocket connection with the browser and monitors changes in native code through webpack exposed apis. When local files are changed, WebPack repackages them. WDS pushes the hash value of the new module to the browser, as shown below
When the browser receives the hash value, it goes to WDS via Ajax and requests the updated list of files
Request the latest module code through JSONP according to the corresponding file list
After that, the old and new module codes will be compared to decide whether to update the module. After deciding to update the module, the dependency relationship between the modules will be checked, and the dependency reference between modules will be updated at the same time.
For more details
6. How to optimize webPack build speed
- Here is not ugly, you can directly see Liu Xiaoxi small sister take you deep unlock Webpack series (optimization), write very good
network
1. What is cross-domain? What are the cross-domain solutions?
Cross-domain refers to the fact that the domain to which the request is initiated is different from the domain to which the resource to which the request is directed is located, triggering security restrictions of the browser. Generally speaking, cross-domain exists as long as the domain name, protocol, and port number of the originating domain and the request domain are different. Solutions are as follows:
- Document.domain + iframe: This method requires the same primary domain, and communicates by setting the pages to communicate with document.domain to the same primary domain.
- PostMessage: This method is used to send messages to a window. The receiving window receives messages by listening for message events. When receiving messages, it is necessary to verify the identity of the sender by judging the Origin and Source attributes, otherwise XSS attacks may occur.
- Jsonp: Basically creates a script tag dynamically and assigns SRC to the request address of the function name with the front-end receiving argument (e.g
src=http://xxx.com? Cb = function name
), the back end receives the request, gets our function name, passes the data as arguments to the function, and returns it to the front end to execute the call.- The advantage of this method is that it realizes cross-domain and has good compatibility
- disadvantages
- Only GET requests can be sent
- When a JSONP call fails, it can only silently fail without error handling
- Security is low and may be subject to XSS attacks
- CORS: The key to cross-domain implementation of this method is the back end, as long as the back end is set up
Access-Control-Allow-Origin
You don’t have to do anything on the front end, but note that with CORS there are two types of requests: simple and complex.- Simple request:
- The request method can be head, GET, or POST
- The request header contains the following fields: Accept, accept-language, content-language, last-event-ID, Content-Type (Only three values application/ X-www-form-urlencoded, multipart/form – the data, the text/plain)
- Complex request: All requests except simple requests are complex requests. Before formal communication, complex requests will send an Option request for pre-check. Only when the server successfully responds to pre-check, the browser will send the corresponding request, otherwise, an error will be reported.
- Simple request:
- Websocket: WebSocket is a new API implemented in HTML5 that itself supports cross-domain, using this method to open an interactive communication session between the browser and the server. Websocket itself provides onOpen, onClose, onMessage, onError, send and other apis, we can call it directly.
- Node agent cross-domain: The node server is set up to forward our requests in the following three scenarios
- If webpack is used: modify the specific configuration of the proxy field under devServer in webpack.config.js
- Create-react-app is used:
- Add the proxy field to package.json. Note that this method can only set one address
- Create the setupproxy.js file in the SRC directory
- Eject then modifies webpack.config.js itself
- No Webpack and no scaffolding: Build a server from Node, use CORS to make it accessible to the front end, and use http-proxy-Middleware to configure proxy information to make request forwarding configuration visible
- The nginx agent is cross-domain: like Node, we build a server to forward our requests, specifically to modify the nginx.conf file, for example
Server {listen Port for starting the service, for example, 8081; Server_name Specifies the name of the started service, for example, localhost. The root agent's project path is D:\\example\\project; Location/API /{in the proxy project, the/API will replace it with the address in proxy_pass proxy_pass Reverse proxy address such as http://x.x.x.x:x/; }}Copy the code
2. What are the common HTTP status codes?
-
1xx: Message response
-
2xx: Successful response
- 200 OK: The request is successful
- 204 No Content: The server successfully processed the request, but did not return any Content
-
3xx: redirection
- 301 Moved Permanently: Permanently redirected. The requested resource has been Permanently Moved to a new location
- 302 Found: Temporary redirection. The requested resource was temporarily moved to another location
-
4xx: Client error
- 400 Bad Request:
- The current request cannot be understood by the server. The client should not re-submit this request unless it is modified
- The request parameters are incorrect.
- 401 Unauthorized: Unauthorized and requires authentication. Login is usually required
- 403 Forbidden: The server denies the client access to the resource
- 404 Not Found: The requested resource does Not exist or the server rejects the request without giving a reason
- 400 Bad Request:
-
5xx: Server error
- 500 Internal Server Error: The Server fails
- 502 Bad Gateway: indicates an incorrect Gateway
- 503 Service Unavailable: The Service is Unavailable
- 504 Gateway Timeout: Indicates that the Gateway times out
-
More status codes
3. Enter a URL to the page display process
- Enter the url
- DNS resolution: Resolves a domain name into an IP address
- IP address search order: browser cache -> operating system cache -> host file -> router cache -> Internet service provider -> root DNS server; It not only returns the IP address to the user’s computer, but also caches the mapping between the domain name and THE IP address so that it can be returned directly on the next visit
- TCP connection: After receiving the IP address, the browser initiates a TCP connection request, also known as the three-way handshake
- Three handshakes: First, the browser sends a SYN packet to the server and enters the SYN_SENT state. After receiving the PACKET, the server returns a SYN + ACK packet and enters the SYN_RECV state. After receiving the packet, the client sends an ACK packet to the server. Complete three handshakes
- HTTP request: After a TCP connection is established, the client sends an HTTP request. An HTTP request contains the request line, request header, and request body
- Request line: contains request method, protocol version, etc
- Request header: contains the custom request header, browser information, request source, and language
- Request body: Data sent. GET requests have no request body
- HTTP response: the response that the server sends to the client after receiving a request, including the response line, response header, and response body
- Response line: contains status code, description of status code, and protocol version
- Response header: contains server information, cache rules, dates, and so on
- Request body: Requested resource
- Page rendering: the browser rendering flow I wrote above
- Connection closing: We have a Connection field in our request and response headers. The default value is keep-alive, so normally Connection closing occurs when the current TAB is closed, and four waves are made
- Four waves:
- The client first tells the server to disconnect and close the input channel
- The server will reply to the client and I will close this channel as well
- The server then tells the client that I want to close the input channel
- The client replies that you turn it off, and I turn off the receiving channel
- The reason why there are two channels is that TCP is a full-duplex connection and both ends have the receiving and sending capabilities. Therefore, the two ends of each channel are receiving and sending
- Four waves:
4. The difference between HTTP and HTTPS
- The HTTP port is 80 and HTTPS is 443
- HTTP communication uses plaintext, while HTTPS uses SSL/TSL encryption
- HTTPS requires a CA certificate, which requires a fee
- HTTP is more efficient than HTTPS because HTTPS requires encryption
5. HTTPS encryption mode
-
Symmetric encryption: Use the same string of keys for encryption and decryption
- Advantages: encryption and decryption time is relatively short, fast
- Disadvantages: not very secure, as there is a risk of interception during key distribution
-
Asymmetric encryption: Encryption and decryption using different secret keys. The encrypted secret key and decrypted secret key are a corresponding set of secret keys, called public key and private key. The information encrypted by the public key can only be decrypted using the corresponding private key, and vice versa
- Advantages: High security, because only the public key is transmitted on the network and the private key is kept in your own hands
- Disadvantages: encryption and decryption takes a long time, slow speed
-
Symmetric encryption + asymmetric encryption: Remove the disadvantages of both and retain only the advantages. Use asymmetric encryption to transfer the symmetric encrypted secret key, and then use symmetric encryption for subsequent communication, which is used in HTTPS
-
Man-in-the-middle attack: Asymmetric encryption of the public key is sent to the client server, but transport process may be blocked by the middleman, so you can use your own public key to the middlemen replace then put false public key is sent to the client, the client then use false public-key encryption symmetric encryption using the secret key, the middleman can use their corresponding decrypted and then get the symmetrical secret key encryption.
- Solution: To solve man-in-the-middle attacks, we need a way to be sure that the public key received has not been changed, or that we know about it, and that way is the CA certificate
-
CA certificate: First, the server information and public key are used to generate a message digest using the hash algorithm. Then, the message digest is encrypted with the private key of a third-party notary office to generate a digital signature. Then, the CA certificate is created by combining the server information, public key, and digital signature. After receiving the CA certificate, we decrypt the digital signature with the public key of the CA institution to obtain the message digest. Then, we encrypt the received public key and the server information with the same hash algorithm to generate a new message digest. By comparing the two message digest, we can know whether the information is modified
security
1.XSS attack (cross-site scripting attack)
- Definition: An attacker injects malicious script code into a web page. The malicious code is executed when the user accesses the page, thus attacking the user
- Classification:
- Stored XSS: The attacker first submits the malicious code to the database through form submission. When the user accesses the web page to obtain the corresponding data, the server will take out the code and return it to the browser. The browser will execute the code in the process of rendering the data to the page
- Reflective XSS: The attacker splicing malicious code into the URL to induce the user to click. After the user clicks, the server will take out the malicious code as a parameter, and finally return it to the browser, which will be executed when it needs to render. For example, the search function interface of a website is xxxx.com/search?key=XX. When the data is empty, the front-end page indicates that XX data is not available, then the attacker changes XX into malicious code and makes the user click the URL. The server takes out the search value without processing it and finally returns it to the browser. Malicious code can be executed
- DOM XSS: Similar to reflective XSS, both use concatenated URLS to induce users to click. The difference is that reflective XSS is executed by sending the URL first to the server and then back to the browser, while DOM XSS is executed directly on the front page. For example, if a page address is xxxx.com? Name =XX, js will render the value of name to the page, if XX is malicious code, then the rendering will be executed
- Prevention:
- Restrict and filter the content and length of specific input such as phone number and URL
- Use innerText for front-end rendering of undefined content
- Set HttpOnly to prohibit JS from reading cookies
Refer to the front-end safety series of Meituan Technical team (I)
2.CSRF attack (cross-site request forgery)
- Definition: An attack method that forces a user to perform unintended actions on a currently logged Web application
- Attack flow:
- The user logs in to a’s website and saves the cookie
- The attacker induces users to click on b’s website
- Web site B will send a request to web site A, and the browser will carry the user’s cookie
- Website A receives the request, checks the login credentials, mistakenly thinks it is the user’s own operation, and then executes the request. The attack is complete
- Features:
- The attack is usually launched after a link is clicked to a third party website
- The user’s login credentials on the attacked site were used to forge user actions
- Unable to obtain user credentials, only impersonation
- Cross-site requests can be made in a variety of ways: image urls, hyperlinks, CORS, Form submissions, and more. Part of the request can be directly embedded in third-party forums, articles, difficult to track.
- In addition to cross-domain attacks by third-party websites, attacks can also be carried out in the local domain if there are comment sections for Posting pictures and links
- The prevention of
- Origin detection: The Origin of the request is determined by the Origin and Referer fields in the HTTP request header
- Origin:
- IE 11 will not add Origin on cross-site CORS requests
- Origin is not included in a redirected request after a 302 redirect
- Referer defects:
- Referer implementations vary from browser to browser
- Attackers can hide Referer in their requests
- When the HTTPS page jumps to the HTTP page, all the browser referers are lost
- Origin:
- Token: The login credentials are cookies. Although an attacker cannot obtain the login credentials directly, the browser carries them. Therefore, you can add a customized request header to each request header that the attacker cannot obtain and the browser does not automatically carry
- Double Cookie authentication: a random string Cookie is proactively added to the request domain during user access, and the Cookie needs to be taken out for each subsequent request and added to THE URL parameter. After receiving the request, the backend compares the parameter with the Cookie
- Defect:
- Additional fields are added to cookies
- If there are other vulnerabilities (such as XSS) where the attacker can inject cookies, this defense fails
- Isolation of subdomains is difficult
- Defect:
- Origin detection: The Origin of the request is determined by the Origin and Referer fields in the HTTP request header
For more information, please refer to the front-end safety Series (ii) of Meituan Technical Team.
The last
The above content is a knowledge point covered by the questions I have been asked in the interview over the past 20 days. In the process of recording, I found that I did not have a comprehensive grasp of many knowledge points before, so I also gained a lot this time. I also hope to provide more or less help to every partner in need. ^_^