In view of the interview rate is relatively high difficult knowledge comb.

Compared to the first article, this article is more relevant to this year’s interview practice. The first one is more comprehensive and more basic. It is recommended to read the previous one first and then this one will be easier to understand.

The first inaccessible post has been fixed. I don't know why, but I reposted it

Common usage of ES6

ES6 (ECMAScript 2015 and beyond) is a common interview question: “Do you usually use ES6? Name a few uses of ES6.

Three or four answers should be enough, but each one needs to be clear, and some interviewers will continue to ask questions.

If you have enough time, you are advised to check out Ruan yifeng’s introduction to ES6.

1.1 the let and const

  • Let is valid in block-level scope and does not contaminate global variables
  • Const cannot be changed once declared. Note that the memory address it points to cannot be changed, if it is an object or an array of properties or elements can be changed.
  • Temporary dead zones exist and cannot be variable promoted.
  • It can only be declared before use, and cannot be repeated

1.2 Character Templates

Used as string concatenation: Hello, ${name}

1.3 Deconstructive assignment of variables

  • Let [a, b, c] = [1, 2, 3]
  • Swap variables: [a,b] = [b,a]
  • Let {data, code} = res
  • Input module specification method:
const { SourceMapConsumer, SourceNode } = require("source-map");
Copy the code
  • Returns multiple values from a function: returns an array or an object

1.4 Extended operators

The spread operator (spread) is three points (…) .

  • Let arr2 = […arr1]
  • Merge arrays: […arr1,…arr2,…arr3]

1.5 Promise

  • A successful callresolve, failed callreject
  • .thenGet results,.catchCatch exceptions. Catching exceptions can also be passed.thenThe second argument to
  • .finallyWill be called regardless of success or failure
  • Multiple concurrent requests, withPromise.all()
    • onlyp1,p2,p3The state of theta becomesfulfilled.pWill becomefulfilledAt this time,p1,p2,p3To form an array of return values passed topThe callback function of.
    • As long asp1,p2,p3One of them wasrejected.pThe state of theta becomes thetarejectedAt this time, the first to berejectIs passed topThe callback function of.
let p = Promise.all([p1,p2,p3])
p.then(([res1, res2,res3]) => {};
Copy the code

Promise the sample:

New Promise(){if (/* succeed */){resolve(value); } else { reject(error); } }.then().catch().finally()Copy the code

1.6 async await

What is async function? In short, it is the syntactic sugar of Generator functions. Async improves Generator functions:

  • Built-in actuator, directly called. The Generator also needs to be callednext() To perform
  • Better semantics.asyncawait*yield A better understanding
  • The return value is Promise

1.7 Arrow Function

This of the arrow function () => {} is bound when the function is defined, not during execution. Simply put, when a function is defined, this inherits the object from which the function was defined. This will not change once determined.

The this of an ordinary function refers to the object on which it was called.

Second, mobile TERMINAL H5 compatibility and adaptation

A common adaptation is the REM + Flex layout.

2.1 rem adaptation

Set the base font size in the app entry, the earlier the better. If the design dimension is 750, divide by 7.5. The specific value is calculated according to the actual situation.

Document. The documentElement. Style. FontSize = document. DocumentElement. ClientWidth / 7.5 + 'px';Copy the code

After setting the base font size, the SASS function encapsulates a method for easy use

@function px2rem($value){@return $value * 0.02rem}Copy the code

When using it, you can directly call the encapsulated function. Value is passed the value of PX, and the method will be automatically converted into REM.

width: px2rem(100)
Copy the code

2.2 Flex layout

Flex Layout tutorial: Syntax by Yifeng Ruan

Iii. Vue related issues

Generally speaking, small and medium-sized companies will ask more framework, the specific Vue or React depends on the technology stack used by the company. Because the technology stack of small and medium-sized companies is relatively unified, it is rare to use two or even three frameworks at the same time, and pay more attention to the ability to work, so the use of the framework will take up half of the interview time.

Big companies, on the other hand, focus less on the framework and more on the basics. Their logic is to see if you have the ability, and if you have the ability to use any framework quickly.

Since I am not familiar with React, I only prepared some questions for Vue. The following are some of the most common interview questions that you must understand.

There is an article on Vue summary of the more complete, here is also excerpted several answers. For the full content, see here: 30 Vue interview questions, including detailed explanations (ranging from beginner to proficient, self-test Vue proficiency level)

3.1 Vue bidirectional binding principle

If asked about the framework, Vue will definitely ask this question. Just memorize the following passage.

Vue implements bidirectional data binding through the following four steps:

  • Implement a listener Observer that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data.
  • Implement a parser Compile: parse Vue template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update.
  • Implement a subscriber Watcher: The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.
  • Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.

Vue3 will replace Object.defineProperty() with a Proxy. What are the advantages of Proxy?

It is recommended to introduce proxy and tell several advantages.

3.2 Implementation principle of virtual Dom

The importance of this topic is second only to the principle of Vue bidirectional binding

The realization principle of virtual DOM mainly includes the following three parts:

  • JavaScript objects are used to simulate the real DOM tree and abstract the real DOM.
  • Diff algorithm — Compare the difference between two virtual DOM trees;
  • Pach algorithm – The difference between two virtual DOM objects is applied to a real DOM tree.

Advantages:

  • Lower performance: The framework’s virtual DOM needs to accommodate any operations that the upper-level API may produce, and some of its DOM operations must be implemented in a universal way, so its performance is not optimal; But performance is much better than rough DOM manipulation, so the framework’s virtual DOM can at least guarantee decent performance without having to manually optimize it.
  • No need to manually manipulate the DOM: We no longer need to manually manipulate the DOM, just need to write the code logic of the View-Model, the framework will help us update the View in a predictable way according to the virtual DOM and data two-way binding, greatly improving our development efficiency;
  • Cross-platform: The virtual DOM is essentially a JavaScript object, and the DOM is platform-dependent. In contrast, the virtual DOM can be more easily cross-platform, such as server rendering, WEEX development, and so on.

Disadvantages:

  • Extreme optimization cannot be carried out: Although reasonable optimization of virtual DOM + is sufficient to meet the performance requirements of most applications, targeted extreme optimization cannot be carried out in some applications with extremely high performance requirements.

In-depth analysis: Vue core virtual DOM juejin.cn/post/684490…

3.3 Route Caching

Use

to cache routes.

It has include and exclude attributes to include or exclude certain routes, respectively. The value can be a string, array, or regular expression.

Unique lifecycle methods: Activited, deActivited

3.4 Route Hops: Difference between Name hops and PATH hops

Several ways to redirect a route

/ / string
this.$router.push('home')

// Named route
this.$router.push({
  name: 'user'.params: {userId: '123'}})// Receive parameters
this.userId = this.$route.params.userId

// with query parameters, change to /user? userId=123
this.$router.push({
  path: '/user'.query: {userId: '123'}})/ / receive
this.userId = this.$route.query.userId;
Copy the code

The difference between name and PATH jumps is that

  • Params is used for name and Query is used for path.
  • The name parameter is not carried to the URL. The query parameter is carried to the URL.

3.5 Route Guard

Global front guard

Be sure to call next(); Otherwise the hook will not be resolved.

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) = > {
  // ...
  next();
})
Copy the code

Global parsing guard

In 2.5.0+ you can register a global guard with router.beforeResolve. This is similar to router.beforeeach, except that the parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components are parsed.

Global post-hook

You can also register global post-hooks, however unlike guards, these hooks do not accept the next function nor change the navigation itself:

router.afterEach((to, from) => {
  // ...
})
Copy the code

Route exclusive guard

You can define beforeEnter guards directly on the routing configuration:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
Copy the code

These guards have the same method parameters as the global front-guard.

Guards within components

Finally, you can define the following route navigators directly within the routing component:

  • beforeRouteEnter
  • beforeRouteUpdate(new) 2.2
  • beforeRouteLeave

Notice that next() is called

const Foo = { template: `... ', beforeRouteEnter (to, from, next) {// Call the render component before the corresponding route is confirmed // no! Can!!!! }, beforeRouteUpdate (to, from, next) {// Called when the current route changes but the component is being reused. For example, For a path /foo/:id with dynamic parameters, the component instance will be reused as // renders the same foo component when jumping between /foo/1 and /foo/2. And the hook will be called in that case. // Call beforeRouteLeave (to, from, next) {// Call beforeRouteLeave (to, from, next) {Copy the code

This section is quite extensive, see the official vue-Router documentation for more details

3.6 The difference between Vue and React

Vue forms can use v-Model to support two-way binding, which is much easier to develop than React. Of course, V-Model is a syntax candy, essentially the same way React forms are written.

React requires the use of setState to change the state, and there are some pitfalls to using this API. In addition, the bottom layer of Vue uses dependency tracking, so page update rendering is already optimal, but React still requires users to manually optimize this aspect.

After React 16, some hook functions will be executed multiple times due to the introduction of Fiber, which will be covered in a later section.

React requires the use of JSX, which has an initial cost and requires a complete toolchain support. However, you can use JAVASCRIPT to control pages, which is much more flexible. Vue uses template syntax, which is less flexible than JSX, but it can be run in a browser by writing the Render function directly out of the toolchain.

In terms of ecology, there is not much difference between React and Vue. Of course, React has far more users than Vue.

In terms of start-up cost, Vue’s initial positioning was to reduce the threshold of front-end development as much as possible. However, React was more about changing users to accept its concepts and ideas, and the start-up cost was slightly higher than Vue.

3.7 Transferring Values between Components

Component transmission is divided into parent-child component transmission and non-parent-child component transmission

Pass values between parent and child components

  • Parent component passes value to child component, directly throughpropsThe value of
<custom Content =" Hello world"></custom> Copy codeCopy the code
  • The child passes a value to the parent, passingemitSend the event
This.$emit('chooseType', type) copies the codeCopy the code

The parent component receives events:

<custom Content =" Hello world" @chooseType="handleType"></custom> Copy codeCopy the code

Non-parent components pass values

Values are mainly passed through the event bus

Mount an empty Vue object on the root node

Vue.prototype.bus = new Vue(); Copy the codeCopy the code

The component that needs to send the event

This.bus.$emit("change", params) copies the codeCopy the code

The component that receives events

this.bus.$on("change", (msg) => {
    //do yourself work
})
Copy the code

In addition to these questions, there are also Vue life cycle, V-show and V-IF, vuEX, etc.

For more tips on Vue development, see my other article: Vue Development Tips

Fourth, modular development

4.1 What is a module

  • Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together
  • The internal data and implementation of a block are private, exposing only interfaces (methods) to communicate with other external modules

4.2 Benefits of modularity

  • Avoiding naming conflicts (reducing namespace pollution)
  • Better separation, load on demand
  • Higher reusability
  • High maintainability

4.3 Modular Specifications

1, the CommonJS

Basic syntax:

  • Exposure module:module.exports = valueorexports.xxx = value
  • Introduction module:require(xxx)If the module is a third-party module, XXX is the module name. For a custom module, XXX is the module file path

Loading a module loads the module.exports property of that module. The require command is used to load module files. The basic function of the require command is to read and execute a JavaScript file and then return the exports object of that module. If no specified module is found, an error is reported. The loading mechanism for CommonJS modules is that the input is a copy of the output value. That is, once a value is printed, changes within the module do not affect that value. This is a major difference from ES6 modularity.

2. ES6 modular

The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.

/** Define the module math.js **/
var basicNum = 0;
var add = function (a, b) {
    return a + b;
};
export { basicNum, add };

/** references the module **/
import { basicNum, add } from './math';
function test(ele) {
    ele.textContent = add(99 + basicNum);
}
Copy the code

You can also use export default

// export-default.js
export default function () {
  console.log('foo');
}

// import-default.js
import customName from './export-default';
customName(); // 'foo'
Copy the code

3. Differences between ES6 module and CommonJS module

There are two important differences:

  • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value.
  • The CommonJS module is run time loaded, and the ES6 module is compile time output interface.

Encapsulate the request and add a public header

Add the header

// Create an axios instance
let instance = axios.create({timeout: 1000 * 12});

// Set the POST header
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.withCredentials=true; // Make Ajax carry cookies
Copy the code

Add the header to the API method

postJson(url, params) {
  return axios.post(`${base}${url}`, params, {
    headers: {'content-type': 'application/json; charset=UTF-8'}})},// The basic get method
get(url, params) {
  return axios.get(`${base}${url}`, {params: params})
},

// The basic post method
post(url, params) {
  return axios.post(`${base}${url}`.JSON.stringify(params))
},
Copy the code

Page performance optimization

Performance tuning is almost a must, and it’s best to mention the following five ways.

The second and third points extend, and the parentheses are the general directions of extension. See page performance for a detailed explanation

Objective: To speed up interface display and reduce the number of data requests.

What are some ways to improve page performance?

  1. Resource compression merges to reduce HTTP requests
  2. Asynchronous loading of non-core code (how to load asynchronously, the difference between asynchronous loading)
  3. Make use of browser caches (cache classification, cache principles)
  4. Use the CDN
  5. Preliminary analytical DNS
<meta http-equiv="x-dns-prefetch "content="on"> href="//host_name_to_prefetch.com">Copy the code

Browser cache

Classification of cache policies:

  • Strong cache
  • Negotiate the cache

Caching policies are implemented by setting HTTP headers. Each time the browser initiates a request, it first looks up the result of the request and the cache identifier in the browser cache. Each time the browser receives the result of the returned request, it stores the result and the cache id in the browser cache.

7.1 strong cache

Strong cache: Does not send a request to the server, but reads resources directly from the cache. In the Network option of the Chrome console, the request returns a status code of 200, and Size displays from Disk cache or from Memory cache. Strong caching can be implemented by setting two HTTP headers: Expires and cache-Control.

1. Expires

Cache expiration time, used to specify the expiration time of resources, is a specific point in time on the server. That is, Expires=max-age + request time needs to be used in combination with last-Modified. Expires is a Web server response header field that tells the browser in response to an HTTP request that the browser can cache data directly from the browser before the expiration date without having to request it again. Expires is a product of HTTP/1 and is limited to local time, which can invalidate a cache if you change it. Expires: Wed, 22 Oct 2018 08:41:00 GMT Indicates that the resource will expire after Wed, 22 Oct 2018 08:41:00 GMT and needs to be requested again.

2. Cache-Control

In HTTP/1.1, cache-control is the most important rule and is used to Control web page caching. For example, cache-control :max-age=300 means that the strong Cache will be hit if the resource is reloaded within 5 minutes of the correct return time of the request (which the browser records). Cache-control can be set in either the request header or the response header, and can be combined with multiple instructions:

3. Compare Expires and Cache-control

The difference is that Expires is a product of HTTP1.0 and cache-Control is a product of HTTP1.1. If both exist, cache-Control takes precedence over Expires. In some environments where HTTP1.1 is not supported, Expires can be useful. So Expires is an outmoded object that currently exists as a way to write compatibility. Strong caches Determine whether or not the cache is cached based on whether or not the server side file has been updated after a certain time or period, which may result in the loading file is not the latest content on the server side, so how do we know whether the server side content has been updated? Here we need to use a negotiated cache strategy.

7.2 Negotiated Cache

Negotiation cache is a process in which the browser sends a request to the server with the cache ID after the cache is invalid, and the server decides whether to use the cache based on the cache ID. There are two main situations:

  • The negotiated cache takes effect, returning 304 and Not Modified
  • Negotiation cache invalid, return 200 and request result

Negotiated caching can be implemented by setting two HTTP headers: Last-Modified and ETag.

1. The last-modified and If – Modified – Since

When the browser accesses the resource for the first time and the server returns the resource, the last-Modified header is added to the response header, whose value is the Last modification time of the resource on the server. The browser caches the file and header after receiving it.

Last-Modified: Fri, 22 Jul 2016 01:47:00 GMT
Copy the code

The next time the browser requests the resource, the browser detects a last-Modified header and adds if-modified-since, which is the last-modified value; When the server receives the resource request again, it compares the value in if-modified-since with the last modification time of the resource in the server. If there is no change, it returns 304 and an empty response body, reading directly from the cache. If the time of if-modified-since is less than the time of the last modification of the resource on the server, the file has been updated, and the new resource file and 200 are returned. But last-Modified has some drawbacks:

  • If the cache file is opened locally, last-Modified is Modified even if the file is not Modified. The server cannot match the cache and sends the same resource
  • Because last-Modified can only be measured in seconds, if the file is Modified in an imperceptible amount of time, the server will assume that the resource is still a hit and will not return the correct resource

Since the cache is not sufficient based on the file modification time, can the cache policy be determined directly based on the file content modification? ETag and if-none-match were introduced in HTTP / 1.1

2. The ETag and If – None – Match

An Etag is a unique identifier (generated by the server) that is returned to the current resource file when the server responds to a request. The Etag is regenerated whenever the resource changes. When the browser sends a request to the server next time it loads a resource, it will add the Etag value returned last time to if-none-match in the request header. The server only needs to compare the if-none-match value sent by the client with the Etag of the resource on the server. It is a good idea to determine whether the resource has been modified relative to the client. If the server finds that the ETag does not match, it sends the new resource (including the new ETag) to the client in a regular GET 200 packet return. If the ETag is consistent, 304 is returned to inform the client to use the local cache directly.

3. Compare the two

  • First, Etag is superior to Last-Modified in accuracy.

Last-modified time is measured in seconds. If a file changes several times within a second, their last-Modified version does not actually show up, but Etag changes each time to ensure accuracy. If the server is load-balanced, the last-Modified generated by each server may also be inconsistent.

  • Second, in terms of performance, Etag is inferior to Last-Modified, because last-Modified only takes time to record, whereas Etag requires the server to compute a hash value through an algorithm.
  • Third, server verification takes Etag as the priority

7.3 Cache Mechanism

The mandatory-cache takes precedence over the negotiated Cache. If mandatory-cache (Expires and cache-control) is valid, the Cache is used directly, and If not, the negotiated Cache (last-modified/if-modified-since and Etag/if-none-match) is used. The server decides whether to use the negotiated cache. If the negotiated cache is invalid, the cache of the request is invalid. 200 is returned, and the resource and cache id are returned again, and then stored in the browser cache. If it takes effect, return to 304 and continue to use the cache.

The difference between strong cache and negotiated cache can be expressed in the following table:

Cache type Form of resource acquisition Status code Send the request to the server
Strong cache From the slow access 200 (from cache) No, cache access directly
Negotiate the cache From the slow access 304 (Not Modified) If yes, the server tells you whether the cache is available

The impact of user behavior on caching

The user action Expires/Cache-Control Last-Modied/Etag
Address enter effective effective
Page link jump effective effective
A new window effective effective
Move back effective effective
F5 to refresh invalid effective
Ctrl+F5 Force refresh invalid invalid

7.4 Comparison between from Memory Cache and From Disk Cache

The size bar in Console Network in Chrome usually has three states

  1. from memory cache
  2. from disk cache
  3. The size of the resource itself (e.g. 1.5K)

Three differences:

  • From the memory cache: Literally from memory, also is the literal meaning, actually this is directly from the memory resources, general won’t request to the server has been loading the resource and cached in memory, when close the page, this resource to be released down to memory, once again back on the same page won’t appear the from the memory cache.
  • From Disk cache: The resource is fetched from the disk and has been loaded at a previous time. The server does not request the resource. However, the resource will not be released when the page is closed because it is stored in the disk and will still be from the disk cache next time
  • Resource size: When the HTTP status is 200, the resource is actually obtained from the browser. When the HTTP status is 304, the resource size is the size of the packet communicated with the server, not the size of the resource itself. The resource is obtained locally
state type instructions
200 form memory cache Do not request network resources, resources in memory, ordinary scripts, fonts, images will be stored in memory.
200 form disk ceche Do not request network resources. In disks, non-scripts are generally stored in memory, such as the CSS.
200 Resource size value Resource size value Downloads the latest resource from the server.
304 Packet size The requesting server finds that the resource is not updated and uses the local resource, that is, matches the negotiated cache.

8. Webpack basic configuration

Webpack is one of the most common questions to ask in an interview for advanced front-end development, and a little preparation is better than nothing

8.1 Basic Concepts

The default configuration file for Webpack is webpack.config.js.

Webpack can only handle JS files by default. If you want to handle other files such as images, you need to use the corresponding Loader. For example, file-loader, URl-loader, CSS-loader, and style-loader. If sass is used, sas-loader is used.

A few other important concepts are:

  • Mode: Specifies the packaging mode, development or production.
  • Devtool: Specifies how to generate sourceMap.
  • Entry: configures the entry file. If multiple files are packaged, several entries are written in the entry, and a placeholder is used for filename output[name]Said.
  • Output: the export.
  • Loader: Various tools to assist packaging.
  • Loaders are used to convert certain types of modules, while plugins can be used to perform a wider range of tasks. Such as HtmlWebpackPlugin, CleanWebpackPlugin.
  • DevServer: Use WebpackDevServer to enable hot update to improve development efficiency.

8.2 HMR thermal overload

Configuration method

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
// Add this line
const webpack = require('webpack');

module.exports = {
  mode: 'development'.devtool: 'cheap-module-eval-source-map'.entry: {
    main: './src/index.js',},output: {
    filename: '[name].js'.path: path.resolve(__dirname, 'dist')},devServer: {
    contentBase: './dist'.open: true.port: 9090.// Add the following two lines
    hot: true.hotOnly: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html"
    }),
    new CleanWebpackPlugin(),
    // Add this line
    new webpack.HotModuleReplacementPlugin(),
  ],
  module: {
    rules: [{test: /\.(png|jpg|gif|jpeg)/,
        use: {
          loader: 'file-loader'.options: {
            name: '[name]_[hash].[ext]'.outputPath: 'images/'}}}, {test: /\.(eot|woff|svg|ttf)/,
        use: {
          loader: 'file-loader',}}, {test: /\.(css|scss)/,
        use: [
          'style-loader',
          {
            loader: 'css-loader'.options: {
              importLoaders: 2.// modules: true}},'sass-loader'.'postcss-loader'}]}}Copy the code

CSS hot reload style-loader and CSS-loader have been implemented for us.

JS thermal overload

// Check whether hot update is enabled
if (module.hot){
  // Listen for sorts. js files and execute the arrow function when the file changes
  module.hot.accept('./hotTest.js'.() = > {
    // The operation performed when the file changeshotTest(); })}Copy the code

8.3 Code and image compression

Compressed JavaScript

At present, the most mature JavaScript code compression tool is UglifyJS, which will analyze the syntax tree of JavaScript code and understand the meaning of the code, so as to achieve optimization such as removing invalid code, removing log output code, shortening variable names, etc.

To access UglifyJS in Webpack, you need to use plug-ins. Currently, there are two mature plug-ins, which are as follows:

  • UglifyJsPlugin: Compression by encapsulating UglifyJS.
  • ParallelUglifyPlugin: Parallel compression for multiple processes.

The compressed image

Compress images using image-webpack-loader

Enable Gzip compression

Enabling gzip also significantly compresses the size.

Nine, security

There are two types of front-end security: CSRF and XSS

Common test points: basic concepts and abbreviations, attack principles, defense measures

9.1 CSRF

Cross-site Request Forgery (CSRF) Cross-site request forgery.

Attack principle

  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.

Defensive measures

  1. Token authentication
  2. Referer validation (simple and easy, but Referer can be changed)
  3. Hide the Token (similar to Token validation, store the Token in the header)

9.2 XSS

XSS (Cross-site Scripting) Cross-domain scripting attacks

Attack principle

Insert malicious Script code into Web pages

Defensive measures

  1. HTML: Escape the following characters:
& : & amp; < : & Alt; > : & gt; ': & # x27; ": & quot; / : & # x2F;Copy the code
  1. Javascript: Escape all non-alphanumeric characters to ASCII characters less than 256;

  2. URL: encodeURIComponent() encodes user input using Javascript’s encodeURIComponent() method, which encodes the following characters:

    , /? : @ & = + $#Copy the code

10. Deep copy shallow copy

Ask JS foundation will generally ask the depth of the copy of the problem, the rate is relatively high

Shallow copy

  1. Object.assign 

  2. Expansion operator…

Deep copy

  1. Parse (json.stringify (object)).

    But there are a few caveats

    • ignoreundefined
    • ignoresymbol
    • Non-serializable function
    • Cannot resolve object referenced by loop
  2. If the object you need to copy has built-in types and no functions, use MessageChannel.

  3. Lodash’s deep-copy function is recommended.

HTTP, HTTPS, HTTP2.0

HTTP related is also important and is often asked.

11.1 Basic Concepts

HyperText Transfer Protocol (HTTP) is an application-layer Protocol used in distributed, collaborative and hypermedia information systems. Simply put, it is a method of publishing and receiving HTML pages that are used to transmit information between the Web browser and the Web server. HTTP works on TCP port 80 by default. The standard HTTP service starts with http:// when users visit websites. HTTP sends content in plaintext and does not provide any data encryption. If an attacker intercepts a packet transmitted between a Web browser and a Web server, the attacker can directly understand the packet. Therefore, HTTP is not suitable for transmitting sensitive information, such as payment information such as credit card numbers and passwords. Hypertext Transfer Protocol Secure (HTTPS) is a Transfer Protocol for Secure communication over computer networks. HTTPS communicates over HTTP, but uses SSL/TLS to encrypt packets. HTTPS is developed to provide identity authentication for web servers and protect the privacy and integrity of exchanged data. HTTPS works on TCP port 443 by default. Its workflow is generally as follows:

  1. TCP Three-way handshake
  2. The client authenticates the server digital certificate
  3. DH algorithm Negotiates the keys of symmetric encryption algorithm and hash algorithm
  4. The SSL encryption tunnel negotiation is complete
  5. The web page is transmitted in encrypted way, and encrypted with negotiated symmetric encryption algorithm and key to ensure the confidentiality of data. The hash algorithm is used to protect data integrity from tampering.

11.2 The difference between HTTP and HTTPS

  • HTTP data is transmitted in plaintext and is not encrypted, which is insecure. HTTPS (SSL+HTTP) data is encrypted, which is secure.
  • To use HTTPS, you need to apply for a Certificate from the Certificate Authority (CA). Generally, there are few free certificates and some fees are required. Certificate authorities such as Symantec, Comodo, GoDaddy and GlobalSign.
  • HTTP pages respond faster than HTTPS, mainly because HTTP uses THE TCP three-way handshake to establish a connection. The client and server need to exchange three packets, whereas HTTPS requires the three PACKETS of TCP and the nine packets of SSL handshake, so the total number of packets is 12.
  • HTTP and HTTPS use completely different connections and use different ports, the former 80 and the latter 443.
  • HTTPS is an HTTP protocol built on TOP of SSL/TLS, so HTTPS requires more server resources than HTTP.

11.3 TCP three-way Handshake

In TCP/IP, TCP establishes a reliable connection through a three-way handshake

  • First handshake: The client attempts to connect to the server and sends a SYN packet (syn Sequence number Synchronize Sequence Numbers) to the server. Syn =j then the client enters the SYN_SEND state and waits for confirmation from the server
  • Second handshake: The server receives and acknowledges a SYN packet (ACK = J +1) from the client and sends a SYN packet (ACK = K) to the client. At this time, the server enters the SYN_RECV state
  • Third handshake: The client receives a SYN+ACK packet from the server and sends an ACK packet (ACK = K +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state to complete the three-way handshake

Reference: www.runoob.com/w3cnote/htt…

11.4 http2.0 optimization

What is a HTTP2.0

Simply put, HTTP/2 (Hypertext Transfer Protocol Version 2, originally named HTTP2.0) is the second major version of the HTTP protocol. HTTP/2 is the first update to the HTTP protocol since the release of HTTP1.1 in 1999 and is based on the SPDY protocol. HTTP2.0 features significant improvements in Web performance without changing HTTP semantics, methods, status codes, URIs, and header fields.

What is the SPDY protocol

What is the SPDY protocol? SPDY is a term of Speedy, meaning ‘faster’. It is an application layer protocol based on TCP protocol developed by Google. The goal is to optimize the performance of the HTTP protocol to reduce load times and improve security of web pages through compression, multiplexing, and prioritization. The core idea of SPDY protocol is to minimize the number of TCP connections. SPDY is not intended as an alternative to HTTP, but rather an enhancement of the HTTP protocol.

The disadvantage of HTTP1. X

  1. HTTP/1.0 allows only one request to be made at a time over one TCP connection, and HTTP/1.1 uses pipelined-line technology that can only partially handle request concurrency. Queue header blocking is still a problem, so clients often establish multiple connections to reduce latency when they need to make multiple requests.
  2. A one-way request can only be initiated by the client.
  3. The information on the request and response headers is redundant.
  4. Data is not compressed, resulting in a large amount of data transfer.

HTTP2.0 characteristics

  1. Binary transmission
  2. multiplexing
  3. The Header compression
  4. Server push
  5. A more secure

Reference: segmentfault.com/a/119000001…

Common request methods

GET, POST, PUT, DELETE, and PATCH

12. Linux Operations

The general linux-related backend asks more and the front-end asks less

Lists all processes running in memory

Ps - aux / / * * * process listed the details of the ps - aux | grep * * *Copy the code

Kill the process

 kill -9 -pid 
Copy the code

Xiii. Algorithm

The algorithm still has to accumulate over time

dichotomy

Binary search, also known as split, is a search algorithm that looks for a particular element in an ordered array. The idea of binary search is as follows:

  1. First, the search starts at the middle element of the array. If that element happens to be the target element, the search process ends; otherwise, the next step is performed.
  2. If the target element is greater than/less than the middle element, it looks for the half of the array that is greater than/less than the middle element, and then repeats step (1).
  3. If a step array is empty, the target element was not found.

The time complexity O(logn) of binary search.

Dynamic programming

Dynamic programming algorithm can solve the problem recursively (or divide-and-conquer) by splitting the problem and defining the relationship between the problem states and states. The basic idea of dynamic programming algorithm is similar to divide-and-conquer method. It also decomposes the problem to be solved into several sub-problems (stages) and solves the sub-stages in sequence. The solution of the former sub-problem provides useful information for the solution of the latter sub-problem. When solving any sub-problem, all kinds of possible local solutions are listed, and those local solutions that are likely to be optimal are retained through decision making, while others are discarded. Each subproblem is solved in turn, and the last subproblem is the solution of the original problem.


More basic JS basic related questions please move to the previous article front-end interview essential skills.

Finally, I wish everyone can get a satisfactory offer~