Explore cross-domain issues (same-origin policy, cross-domain problem solutions (no detailed configuration methods, just ideas), raise questions and research results); explore js and callback functions, and a complete explanation of URL and parameters

1. Why can asynchronous data be obtained through callback? How to understand the callback function?

        At the beginning, I knew that the callback function could get asynchronous data, but I was never very sure about the method of getting the data. Today I read a blogger’s explanation which is very good. In fact, it’s easy to understand. The callback function literally means to call it later . The literal meaning of callback is to call back. The callback function generally has a basic condition, passing one function as a parameter to another function. For example, function A is passed as a parameter to function B, then A is the callback function of B.

2. So what is the use of callback function? And why can we get asynchronous data?

        The callback function can ensure the execution of our function. For example, if you want to print 1 first and then 2, if 1 is a time-consuming operation, according to the event loop of js, we know that the result will be 2 1, because the time-consuming operation, that is, the asynchronous operation will It is thrown to the browser to wait for execution, but if print 2 is used as the callback of the print 1 function, the execution order of the function can be guaranteed, which is always 1 2. So why can the second one get the asynchronous data? I have always had a misunderstanding here. I thought that the callback function is also an asynchronous task, so I can get asynchronous data. In fact, it is not the case. The callback function is a synchronous task, but because it is placed inside the asynchronous task, although it is synchronous code, it is wrapped It is an asynchronous task, which is equivalent to doing it tomorrow. Even if it is synchronized, it cannot be reflected today. It is not his turn yet. Just like the code in the example below, callback() is a synchronous task, but it is placed in the asynchronous method setTimeout. inside, so he will not execute it immediately. When waiting for the asynchronous task to be executed, there are two synchronous tasks immediately: console (1) and the callback function. This is why he can get the asynchronous data, which is equivalent to your Go to a coffee shop and order, because making coffee is a time-consuming process. You definitely can't order a coffee and get it immediately. Then you have no choice. You leave your phone number, then go shopping, and wait for it. Call him callback, so that the waiting time can be used for shopping. The phone number left here is the callback() function. Only when the coffee is ready will he call you, which is equivalent to calling the function. The phone number is you The written function will be executed when the clerk calls you .

Code example:

function print1(){

console.log(1)

}

function print2(){

console.log(2)

}

耗时操作:

function print1(){

setTimeout(()=>{

console.log(1)

},500)

}

函数作为参数(保证函数的执行顺序):

function print1(callback){

setTimeout(()=>{

console.log(1)

callback()

},500)

}



function print2(){



console.log(2)



}

print1(print2)

3. Why is JavaScript single-threaded?

        Because the main purpose of JavaScript is to interact with users and operate the DOM, if the user adds a piece of information and then deletes it, the information must be generated first before the deletion operation can be performed. Single-threaded operation can only perform one thing at a time. , then some tasks are very time-consuming and will block the execution of the code. For example, when you open a video while watching it, it may take time for the video to load, but you can still like and vote, so we put the code It is further divided into synchronous code and asynchronous code. The synchronous code will immediately join the JS engine (js main thread) for execution and wait in place, while the asynchronous code is first put into the host environment (usually the browser environment to handle asynchronous tasks ), no need to wait, no blocking of the main thread, asynchronous results will be executed in the future

4. What is a macro task? What are microtasks?

       Code is divided into synchronous code and asynchronous code, and asynchronous code is divided into macro tasks and micro tasks.

        Macro tasks include: script (overall code), seTimeout, setInterval, setImmediate, I/O (Ajax requests and data transmission to the background are all macro tasks), etc.

        Microtask: promise.then() catch() (promise itself is synchronous, asynchronous is its then and catch) process.nextTick()(node), async/await, object.observe, etc.

        The following figure explains what the js event loop is, and also explains why there is an event loop:

Cross-domain issues:

        Cross-domain issues are based on the browser. Due to the existence of the browser's same-origin policy, we first introduce what the same-origin policy is. The same-origin policy is an important security policy for the browser. The source consists of the protocol, host name, and port number. Yes, generally the front end needs to configure an interface when requesting background data. The interface we request is actually composed of Baseurl + interface name. So what is Baseurl? This is a name I like to call. For example, if I need to request the data I need from the http://test.yee.com/auth/role/list address, then we

        Analyze this URL. The first one is the protocol name. The ones we usually see more often are http and https. The next one is the domain name (host name). The domain name (host name) is where we request resources. It can be understood that we provide resources. IP, if you write a local server to provide data when you test by yourself, then this domain name (host name) IP is our own computer IP. In layman's terms, it is the address of our resources, and the virtual directory part is The front-end has many contacts. This is the interface address we configure in the API. In fact, it can be understood by analogy with the local directory. Since network requests have security and verification issues, there are additional protocols in front. In fact, protocol + The domain name (host name) is understood as the local directory as the root directory, and the virtual address is the path we usually take to get some local resources. Accessing the url means we get the data from the external server. The url is a path to get the data. After resources, as for how to display them to users, that is the working part of the front end; then go back and introduce a complete URL. A complete URL generally looks like this: http://www.example.com:8080/role/list? name=123&password=123456#people

A complete url, this is all its components.

1. Agreement:

        The protocols are generally http and https. The data transmitted by http is usually in clear text. The risk is that once the data is hijacked, the other party can easily understand your information, so this is not suitable for transmitting some more confidential information. information, such as bank card passwords, etc., and https is the encrypted version of http. It uses SSL to encrypt the transmitted information. In this way, even if the other party hijacks the data, it cannot intuitively understand the content of the information and requires a key. Convert ciphertext into plaintext, there are many things worth exploring, such as symmetric encryption, asymmetric encryption, digital certificates, single and two-way authentication, etc., ending with // as the delimiter.

2. Domain name (host name):

        www.example.com is the domain name part of the URL. Domain names generally have a certain degree of recognition, such as www.bilibili.com , www.baidu.com , etc., but there is something to note here. For example, if we start the server locally, Then our domain name or host number is our IP. For example, 192.168.31.1 is our host number. We can directly request data here, but the domain name here is not the host number or IP address. This involves another knowledge point. , which is DNS domain name resolution, so its function is actually to resolve our domain name into the corresponding IP address, because we are establishing communication between two IPs, and find the corresponding IP address based on the domain name, which is somewhat like a mapping relationship. Why? It is easy to understand to do this. For example, you may remember www.bilibili.com for a while, but if it is www.192.168.31.1.com , the recognition is very low and difficult to distinguish, so with this step, it is also Why you can find the corresponding website by entering the domain name is because there is a process of DNS domain name resolution.

3.Port:

        I don’t have a deep understanding of ports. The default port number is: 80 or 8080. When I use nodejs to write server-side code, I need to write a port number for detection at the beginning. Here is a guide to help understand, in the hardware Domain, port is also called interface.

4. Virtual directory part: (non-required part of url)

        From the first / to the last / of the domain name, the virtual directory is the interface address for front-end development. People who use computers can understand the local directory. It is not a necessary part. For example, if it is not written here, it usually means accessing a Home page or login page of the website

5. Parameter part:

        The parameter part is from? The # part at the beginning is also called the search part and the query part. Parameters generally allow multiple parameters, and parameters are separated by &. http://www.baidu.com/?wd=Can I eat on an empty stomach? Here is an example. Can I eat on an empty stomach? Our parameter part consists of parameter name wd and parameter value. However, it generally cannot be used to transmit data such as account passwords because it is generally unsafe to display it in plain text. In my picture For example, if the plain text is displayed, others will know your important information at a glance. However, I just discovered a magical place. I copied a URL containing plain text from Baidu and pasted it to be encrypted. It should be simply encrypted. Making it difficult to obtain the plain text content.

6. Anchor part: (no more detailed explanation found)

        From the beginning to the end of #, there is something called anchor jump in CSS, which is to name the class attribute of the div as id="people", and then specify href="#prople" for a link, and then click to jump Go to the div position, then I understand this is where to freeze your screen when you enter a page? Generally it is not set, it is at the top. If it is defined to the bottom element, it may be automatically drawn to the bottom as soon as it comes in. I guess this is what it means (personal feeling)

        Here we have introduced the complete components of a URL. The main purpose is to introduce the port number, because generally we cannot see the port number at our URL and during the URL copy and paste process. It may be a bit unfamiliar. Our cross-domain issues are mainly related to The protocol, domain name, and port number are all different from each other. As mentioned earlier, the source is determined by these three. So why is there this security policy? Because there is some relatively important information in the browser. Although our account and password are stored on the server, an important thing called a cookie is stored in the browser. When you establish a connection with the server for the first time, in order to facilitate subsequent Continuing, the server will return a cookie to the client. With this cookie, the client can directly request data from the server without verification next time. Assuming that the browser does not have a same-origin policy, then a server operates local browsing through js code. The server gets the cookie between it and another server, then he can establish a connection with another server by bypassing the login, so that he can use your identity to do some bad things. In order to prevent this from happening , the browser has formulated a same-origin policy, which is the basic protection.

How to deal with cross-domain issues? There are generally three solution strategies

1.JSONP principle:

        In fact, the src of <script><link><img> can not only fill in the image resource connection or js external link, etc., but also can link to an interface URL, but the function name of the callback function needs to be assumed at the link, so that the server can When returning data, you can return a js code that calls the callback function, and return the data as a parameter, so that you can get the returned data. The disadvantage is that you can only initiate a get request but not a post, etc.

2.cors:

        It is said that this is the most fundamental solution and requires back-end programmers to implement cors configuration.

3.proxy proxy (generally used for local development)

        The most commonly used proxy in daily development is to configure the proxy. Its principle is also very simple. When the client requests resources from a cross-domain website, it intercepts the request and then sends the network request to the target server through the local proxy server. The same-origin policy that I spent a lot of effort introducing before is based on browsers and does not exist between servers. I would like to add some explanations. In fact, under the influence of the same-origin policy, the client still sends data to the server. , the server also responded, but when the returned data reached the client, it was rejected by the client.

4. Question raising and exploration:

        I wonder if anyone will have such a question, isn't the purpose of the same-origin policy to solve security problems? Then with the proxy server avoiding the same-origin policy, server A can't get the existence of the cookie? In this way, I need to introduce some concepts of cookies and sessions in detail (maybe the foundation is not solid, and this concept has been forgotten, so this question arises)

        The one that exists on the server is called session, and the cookie that exists on the client can be understood as cookie is the key and session is the lock. Then this can explain why there is no security problem in getting data from the proxy server because of the browser's same-origin policy. , server A cannot get the cookie sent to the browser by server B through the browser, so can it get it from the proxy server? Obviously it's not possible. Although the proxy server can help forward network requests, you can't ask server B for the cookie it gave to the browser, right? At the beginning, it was introduced that sessions and cookies only exist between the server and the browser. There are only sessions between the server and the server. The two locks cannot open each other. This is obviously unreasonable, so this way we can avoid the same origin policy and get the corresponding lock. The data on the server is saved and the security issues that the browser is concerned about are avoided.

        There is also an nginx reverse proxy. Due to my limited level, I have not yet covered the corresponding knowledge. If I do, I will share it as soon as possible.

Guess you like

Origin blog.csdn.net/weixin_54515240/article/details/129367276