Yesterday went to interview 4399 company front position, this should be my second interview, did not enter the second face, a little uncomfortable. I felt fine after the interview, but when I went back to review, I found that MANY of the questions the interviewer asked me were wrong. Still have to continue to work hard, I hope to get the desired offer as soon as possible. Here is a summary of the interview topics.

directory

  • The difference between mandatory and negotiated caching

  • The difference between setTimeout and promise

  • The difference between cookies and sessions

  • How does Vue implement landing interception

  • What is Vue Navigation Guard

The difference between mandatory and negotiated caching

When the interviewer asked me this question, I was a little confused and thought it was local storage technology, so I said localStorge, SessionStorge, indexDB…

The browser cache mechanism is well illustrated by a graph found on the web

Browser cache

What is mandatory caching

When a browser sends a request, it first fetches a header from the resource cache. If a cache-control or expires expires message is matched, the browser fetches the resource directly from the browser instead of sending the request to the browser. The status code returned is 200 OK (from memory cache) or 200 OK (from disk cache);

Mandatory cache

  • Max-age Calculates a resource expiration time based on this value. If the request time is earlier than the expiration time, the cache is hit

  • No-cache: no local cache is used. Cache negotiation is required to verify with the server whether the returned response has been changed. If there is an ETag in the previous response, the request will be verified with the server. If the resource has not been changed, the re-download can be avoided.

  • No-store: directly forbids the browser to cache data. Each time the user requests the resource, a request will be sent to the server, and the complete resource will be downloaded each time.

  • Public: can be cached by all users, including end users and intermediate proxy servers such as CDN.

  • Private: the device can be cached only by the browser of the terminal user and cannot be cached by a trunk cache server such as the CDN.

What is negotiated cache

Negotiated caching is when the browser sends a request to the server to let the browser know If the cache is available. The request carries the header field information (last-modified/if-Modified-since and Etag/if-none-match) returned from the first request. The server checks whether the result is a cache match based on the header information in the request. If a match is found, the browser returns a new header information to update the corresponding header information in the cache, but does not return the resource content.

Negotiate the cache

The difference between setTimeout and promise

I have known about this question, but I did not answer it clearly in the interview, which was a little general

Both setTimeout and promise can be used to handle asynchronous operations. How do synchronous and asynchronous tasks perform

Enforcement mechanism

Event Table
Event Queue

What are macro tasks and micro tasks

So let’s start with the last picture, which is so illustrative

Macro and micro tasks

The Event Queue includes macro tasks and microtasks. Common macro tasks include Script, setTimeout, setInterval, and microtasks include Promise and process.nexttick

Give an example to illustrate the execution process

setTimeout(function() {
    console.log('setTimeout');
})

new Promise(function(resolve) {
    console.log('promise');
}).then(function() {
    console.log('then');
})

console.log('console');
Copy the code

This code enters the main thread as a macro task and is read from the top down

  • First readsetTimeoutRegisters and dispatches its callback function to the macro task event queue
  • And then I ran intoPromise.new promiseWill be implemented immediately. WillthenThe callback function is dispatched to the microtask queue
  • Finally meetconsoleExecute the output immediately
  • After the execution of the first macro task, the current microtask event queue is entered, and the output is executed. The first event loop ends
  • To start the second loop, first read the macro task queue…

So this code outputs the order: Promise, console, then, setTimeout

The difference between cookies and sessions

When the interviewer asked about the difference between session and Cookie, I answered the difference between sessionStorage and Cookie, because I didn’t know about session before

Cookie we should be quite clear, it can store data on the client, sent to the server when the request, can be used to store user information or authentication; Session data is stored on the server. The main differences between the two are as follows:

  • Cookies are not very secure. Others can analyze the cooike stored locally and cheat the server. Session should be used if security is considered

  • Sessions are stored on the server for a certain amount of time. When the number of accesses increases, the performance of the server will be reduced

  • There is a limit to how much data can be saved using cookies

So I think the best practice is to use both together based on business needs

How does Vue implement landing interception

Vue navigation guard intercept

BeforeEach registers a global front guard to determine whether a forward route requires login permission

Step 1 Add the route permission

const routes = [
    {
        path: '/'.name: '/'.component: Index
    },
    {
        path: '/repository'.name: 'repository'.meta: {
            requireAuth: true.// Add this attribute to indicate that login is required to enter this route
        },
        component: Repository
    },
    {
        path: '/login'.name: 'login'.component: Login
    }
];
Copy the code

The second step is to use the VUE navigation guard

router.beforeEach((to, from, next) => {
    if(to.meta.requireauth) {// Determine whether the route requires login permissionsif(store.state.token) {// Whether the token exists through vuex state next(); }else {
            next({
                path: '/login'Query: {redirect: to.fullPath} // Redirect to this route after successful login})}}else{ next(); }})Copy the code

This login interception has two disadvantages:

  • Is simple front-end routing control and does not really prevent users from accessing routes that require login permission
  • When the token expires, the token is still stored locally

Therefore, it is necessary to combine the HTTP interceptor and the status code returned by the back end to determine

Intercept HTTP requests and responses using axios interceptors

If the back-end interface detects that the token expires, return 401 Unauthorized to allow the user to log in again

/ / HTTP request interceptor axios. Interceptors. Request. Use (config = > {if(store. State. Token) {/ / judge the existence of a token, if they exist, are each HTTP headers and token config. The headers. The Authorization = ` token${store.state.token}`;
        }
        return config;
    },
    err => {
        returnPromise.reject(err); }); / / HTTP response interceptor axios. Interceptors. Response. Use (response = > {return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case401: // return 401 to clear token information and jump to login page store.com MIT (types.logout); router.replace({ path:'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        returnPromise.reject(error.response.data) // Return the error message returned by the interface});Copy the code

What is Vue Navigation Guard

Navigation indicates that the route is changing, and you can deal with these changes by observing the $Route object.

conclusion

Because I wrote the VUE framework in my resume, the interviewer wanted to know a lot about VUE. Such as how to implement login permission, when there is no permission how to deal with.. I feel that MY answer is not very good, because I have less project experience and have not encountered similar scenes. In general, this interview gives me a feeling that I lack both basic and practical experience. I will supplement the rest of the content after I have studied deeply for a period of time.