1. The json:
Json: The most common cross-domain method, the principle behind it is to use the script tag SRC to be not restricted by the same origin policy, and dynamically insert script in the page. The SRC attribute of the script tag is the address of the back-end API interface, and the front-end callback handler name is told to the back-end in the way of GET. The back end returns the callback function in response to the request and passes the JSON data back as parameters
const jsonp = ({ url, params, callbackName }) => { const generateURL = () => { let dataStr = ''; for(let key in params) { dataStr += `${key}=${params[key]}&`; } dataStr += `callback=${callbackName}`; return `${url}? ${dataStr}`; }; return new Promise((resolve, Reject) = > {/ / initializes the callback function name callbackName = callbackName | | math.h random (), toString. Replace (', ', '); // create a script element and add it to the current document let scriptEle = document.createElement('script'); scriptEle.src = generateURL(); document.body.appendChild(scriptEle); // Bind to window in order to call window[callbackName] = (data) => {resolve(data); / finished/script execution, become useless elements, to clear the document. The body. The removeChild (scriptEle); }}); }Copy the code
Express response operation:
let express = require('express') let app = express() app.get('/', function(req, res) { let { a, b, callback } = req.query console.log(a); // 1 console.log(b); Res.end (' ${callback}(' packet ') '); }) app.listen(3000)Copy the code
Front-end usage data:
Jsonp ({url: 'http://localhost:3000', params: {a: 1, b: 2}}). Then (data => {console.log(data); // packet})Copy the code
2. The cors:
Cross-origin Resource Sharing is a mechanism that allows resources (such as HTML/JS/Web services) in the current domain (Origin) to be accessed by scripts in other domains (Origin).
Browsers classify CORS requests into two categories: Simple request and not-so-simple Request.
The browser classifies the requests according to the request method and the specific fields in the request header. Specifically, the rules are as follows: The request method is GET, POST, or HEAD. Accept, accept-language, content-language, Content-Type(Only three values application/ X-ww-form-urlencoded, multipart/form-data, text/pl) ain
Simple request: When sending a network request, the browser automatically adds an Origin request header with the value of protocol + domain name + port if it finds a violation of the same Origin policy. After receiving the request, the server will return a normal HTTP response if the source specified by Origin is not within the permitted range. Access-control-allow-origin = access-Control-origin = access-Control-allow-Origin = access-Control-allow-Origin = access-Control-allow-origin
Non-simple request: CORS requests that are not simple requests add an HTTP query, called a “preflight” request (option method), before formal communication. The browser first asks the server whether the domain name of the current web page is on the server’s license list, and which HTTP verb and header fields can be used. The browser issues a formal XMLHttpRequest request only if it receives a positive response; otherwise, an error is reported. Precheck request message:
OPTIONS/HTTP/1.1 Origin: current address Host: xxx.com access-control-request-method: PUT access-Control-request-headers: X-Custom-HeaderCopy the code
Specific process:
- If Origin is not a licensed source, the server will return a normal HTTP response after receiving the request. The browser realizes that the response header does not contain the Access-Control-Allow-Origin field (more on that below), and it throws an error that is caught by XMLHttpRequest’s onError callback. Note that this error cannot be identified by the status code, because the status code for the HTTP response might be 200.
- If Origin specifies a domain name within the license, the server returns a response, Access-control-allow-origin: the value of access-Control-allow-origin is the source address of the request (http://127.0.0.1:8888 is the Origin value). The browser will determine if the access-Control-allow-Origin value is the same as the current address, and if the match is successful (* is a wildcard character, indicating that all are accessible).
Reverse proxy Nginx:
The forward proxy helps the client access servers that the client cannot access on its own, and then returns the results to the client. The reverse proxy takes requests from clients and forwards them to other servers. The main scenario is to maintain load balancing of the server cluster. In other words, the reverse proxy takes requests from other servers, selects an appropriate server, and forwards the requests to it. Therefore, the difference between the two is obvious. A forward proxy server does things for clients, while a reverse proxy server does things for other servers. For example, if the domain name of the client is client.com and the domain name of the server is server.com, and the client sends Ajax requests to the server, of course it will cross the domain, then let Nginx come into play with the following configuration:
server { listen 80; server_name client.com; location /api { proxy_pass server.com; }}Copy the code
Nginx acts as a leapfrog, whose domain name is also client.com, allowing clients to first visit client.com/api, which of course is not cross-domain, and then the Nginx server acts as a reverse proxy, forwarding requests to server.com. When the response is returned, it is sent back to the client, completing the entire cross-domain request process.
Friendship tip: some of the above content is that others write good, take their own summary of the specific text link as follows: juejin.cn/post/684490…