Cross domain
Cross-domain: On the Web, files are served by servers, which determines that files themselves have a concept of source [host, port, protocol]. Two files that are not in the same domain but interact are called “cross-domain.”
Internet Explorer does not include the port number in the check of the same-origin policy
In Postman and the client APP, each request is a separate request for a resource, rather than a page returned by one site and a request for another site/port. So it’s not going to cross domains.
Why cross domains? – Because you do not want to put all resources on one server, this situation is often resolved by changing the domain name
Actual resource interaction occurs in different scenarios, including iframe same-origin restriction, HTTP request restriction and other cross-domain solutions:
- Spurious homology condition
- To a proxy with the ability to cross domains, such as a server
- Using a browser does not limit cross-domain request methods JSONP, postMessage
- Data bodies shared using cross-domain resources
- LLDB: HTTP header communication is allowed to cross – domain
The same Origin policy of the browser: HTTP cross-domain restriction, Cookie cross-domain restriction, IFrame cross-domain restriction, and LocalStorage cross-domain restriction
Iframe displays documents from different sources than top-level documents
For related security issues, check out another blog
Proxy server
Cross-domain access is really just the same origin policy of the browser, the server does not have this restriction
- Node.js HTTP modules and so on can crawl pages from other websites.
- Give the back-end server the address that the front-end Ajax needs to access across domains
Nginx HTTP Proxy service, Reverse proxy server (HTTP middleware)
- Forward proxy: The proxy client initiates a request. A proxy application that is known to the client but transparent to the server (the server does not know who is accessing it) is called a forward proxy. Such as: the ladder
- Reverse proxy: a proxy server that has several built-in servers that users can access.
Nginx reverse proxy is used to transfer requests from the real server to the local server to avoid the “same origin policy restriction” of browsers.
Deploy the nginx reverse proxy server in the same origin of the browser, and configure the port to listen for forwarding requests in the nginx.conf configuration file
Vue-cli devServer and Webpack Dev Server changeOrigin solution to cross domain is essentially a server proxy, just like Nginx reverse proxy
JSONP JSON with padding
It’s basically not used now
The SRC attribute of the < script > tag is not bound by the same origin policy and can be taken from any script on the server and executed
Principle: Allows the server to integrate Script tags back to the client, through the form of javascript callback to achieve cross-domain access. Compared to IMG image detection, it can achieve two-way communication. It is essentially making an HTTP GET request
<script src="http://dohpi? param1=a¶m2=b&callback=jsonp"></script>
<script>
function jsonp(data) {
console.log(data)
}
</script>
// jQuery also supports JSONP methods
// jQuery.getJSON()
$.getJSON(url,[data],[callback])
// You can also specify the name of the callback function in the URL
script.src = 'http://free.net/json/?callback=handleRequest'
Copy the code
- Unsafe: Vulnerable to XSS attacks (to request data from another domain, in case it’s a script, then inject it into your own code)
- Polluted namespace: loaded JS does not have a separate global namespace compared to module JS, and shares a global namespace with the current JS
CORS
Requires both browser and backend support
- Back – end: If the server supports CORS, set access-Control-allow-origin to configure accessible domain names
- Front-end: The browser detects the corresponding Settings and automatically communicates with the corresponding CORS
The browser determines whether the request is cross-domain, and all cross-domain JS requests are submitted. How does the browser know? If CORS is configured on the server, simple request and not-so-Simple Request are processed.
Simple request:
- HEAD
- GET
- Partial POST (Header: Application/X-www-form-urlencoded, multipart/form-data or text/plain)
Complex request:
- The browser first initiates a preflight request using the OPTIONS method to know whether the server will allow the cross-domain request.
- The actual HTTP request is made only after the server confirms that it is allowed.
- In the return of the precheck request, the server side can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data).
Preflight Request: Sent using the OPTIONS method and containing the following headers
- Origin: the requester declares its own source
- Access-Control-Request-Method:
- Access-Control-Request-Header:
The S side determines whether to allow the domain access and automatically adds the header information of the cross-domain request configuration (as follows)
- Access-Control-Allow-Origin
- Access-Control-Allow-Credentials
- Access-Control-Expose-Headers
- Access-Control-Max-Age
- Access-Control-Allow-Methods
- Access-Control-Allow-Headersdocument.domain
document.domain
It can only be used for data communication between domains with the same primary domain name (must belong to the same basic domain name, protocol and port).
When the primary domain communicates with each other, as long as the document.domain of both is assigned to the current primary domain address, cross-domain communication can be realized. Document.domain can be expanded in scope and expansion is irreversible
e.g:
a.second.com:3000/a.html
b.second.com:3000/b.html
Document. domain = ‘second.com’ indicates that the same secondary domain name can be implemented across domains
Real-time two-way Web technology
HTML5 proposes a WebSocket library, while the Node.js backend uses WS module support. Make sure your browser supports it before using it. HTTP is one-way communication, only the client requests the server to respond, but Websocket is two-way, both sides can actively send messages to each other. Websocket requires HTTP to complete the handshake. After the handshake, the two parties communicate with each other using webSocket, which has nothing to do with HTTP.
postMessage(H5)
Then: Cross-source or inter-window communication needs to go through the server
The window.postmessage () method provides a controlled mechanism to circumvent this limitation and, when used correctly, can safely implement cross-source communication, that is, between execution contexts (different worker threads, pages from different sources). Commonly used to retrieve third-party page data embedded in a page. One page sends the message, and the other determines the source and receives the message
// Send the message
otherWindow.postMessage(message, targetOrigin, [transfer]);
/* otherWindow is a reference to another window, such as the contentWindow property of iframe, the window object returned by executing window.open, or the window.frames named or numeric index. Data that message will send to other Windows is serialized by a structured clone algorithm. This means you can safely pass data objects to the target window without having to serialize them yourself. TargetOrigin specifies which Windows receive message events via the origin property of the window, and can be a string "*" (for unrestricted) or a URI. * /
// Receive the message
var mc = new MessageChannel()
mc.addEventListener('message'.event= > {
var origin = event.origin || event.originalEvent.origin
if (origin === 'http://test.com') {
console.log('Verified')}})Copy the code
If any of the protocol, host address, or port of the target window does not match the value provided by targetOrigin, the message will not be sent. A message will only be sent if all three match.
Network request
Essence: browser and server communication
- Java applets, Flash movies
- Remote scripts, embedded Windows
- Ajax Asynchronous JavaScript+XML technical concept: request additional data without refreshing the page
- XHR object
- Fetch API
XMLHttpRequest object same/different step
XMLHttpRequest object FETCH API
By default, XHR only allows access to resources in the same domain as the page that initiated the request. To achieve cross-domain XHR, start from implementing cross-domain HTTP, CORS method, CSP header. In addition, it is also possible to use other non-cross-domain methods, such as JSONP and IMG image detection without XHR
An xsync (configuring the arguments to the open method to implement the same/different steps) call object that sets up the function that responds to changes in the status of the HTTP request
let xhr=new XMLHttpRequest(); // After receiving the response, Xhr.onreadystatechange =function(){if(xhr.readyStatus==4){ if(xhr.status>=200&&xhr.status<300||xhr.status==304){ alert(xhr.responseText); }else{alert("Request failed: "+xhr.status); }// use this instead of XHR to prevent scope problems}}; Xhr.open ("get","./url", Boolean value for whether the request is asynchronous); // Change add should be done at this point xhr.send(request body); // No request body, passed nullCopy the code
The browser’s own default HTTP headers are carried along, and developers can use setRequestHeader () to send custom headers between open() and send()
attribute
- ResponseText: The text returned as the response body
- ResponseXML: when the response body is XML
- Status: indicates the HTTP status of the response
- StatusText: HTTP status description of the response
- ReadyState: At what stage of the request/response process, 0-4, will trigger the readyStatechange event. To ensure cross-basin compatibility, the onReadyStatechange event handler should assign a value before calling open ().
- Timeout: the number of milliseconds that do not respond to a timeout event. An error is reported when accessing state after a timeout. Write a catch/try in onreadyState
There are other progress events: loadstars, Progress, Error,
readyState
Status is the server’s response to the request, and readyState indicates the client’s interaction status process. Ajax. readyState is obtained when an Ajax object interacts with the server. Regardless of the result of the access, running Ajax must experience the state, namely the Ajax run step. (Consists of 1 to 4 digits)
0 – (uninitialized) The send() method has not been called
1 – (load) Send () has been called and the request is being sent. 2 – (load completed) Send () has been executed. 3 – (interaction) Parsing the response
Listening to readyState can be invoked immediately after parsing
A get request
The query string parameters added after the GET request must be properly encoded to be added to the URL and then passed to the Open () encodeURLComponent encoding, & to split all name/value pairs
You can customize addURLParam() to ensure correct encoding
function addURLParam(url,name,value){ url+=(url.indexOf("?" ) = = 1? "?" : "&"); url+=endodeURIComponent(name)+"="+endodeURIComponent(value); return url; }Copy the code
A post request
Send the data that should be saved to the server. The submitted data should be carried in the request body. The data can be in any format
By default, a POST is not the same as submitting a form for the server. Submitting a form can be told to the server by adding the content-Type header, and then serialize the form data as the request body by calling the serialize function. In addition, XHR 2 added the FormData class, which holds the FormData directly as the request body, without adding a special header.
const form = document.getElementById('iii');
xhr.send(serialize(form));
xhr.send(new FormData(form));
// You can also add data like this
FormData.append('key'.'value')
Copy the code
Fetch the API asynchronous
Fetch API tutorial – Ruanyifeng.com
Promises are supported, service workers can perform all tasks of XHR objects, but are easier to use, and are tools that use JS to request resources. The fetch method sends a request to a specified URL and is exposed to a global scope that includes the main page execution thread, the module, and the worker thread.
Let r=fetch('/ resource URL '); // Return a promise r.hen ((response) => {response.text})Copy the code
Get binary data
The data that the back end usually returns to us is in JSON format, but there are other formats as well
In the past, to obtain binary data, the overrideMimeType method of the XMLHttpRequest object was used to override the MIME type of the obtained data and change the character encoding charset of the obtained data to a user-defined type. The XMLHttpRequest object in HML5 has added responseType(attribute values below) and Response attributes
Arraybuffer: Response is a JavaScript arraybuffer that contains binary data.
Blob: Response is a BLOB object that contains binary data. Document: Response is either an HTML document or an XML XML document, depending on the MIME type of the received data. Json: Response is a JavaScript object. This object is obtained by parsing the received data type as JSON. Text: Response is a text represented as a DOMString object.
Beacon API
Is a javascript-based Web API, a very useful method of logging movement, can send data from the page back to the server, especially in the logging environment, browser support is very broad, can record data seamlessly without affecting the user experience and Web page performance. The non-blocking nature of the request means that performance is much faster than alternatives such as XHR and Fetch.
Information is small and fast
- Requests can be successfully sent with conditions like Unload without affecting the next page loading
- Called at any time, the browser adds the request to an internal request queue, and the browser actively sends the request in the queue.
- The browser guarantees that the request will be sent even if the original page is closed.
- Add a sendBeacon() method to the navigator
Navigator.sendbeacon (' URL ', payload parameter of data);Copy the code
web Socket
- Supported by all major browsers
- Is a full-duplex, two-way communication channel with the server that does not use HTTP, but a custom protocol. The goal is to send small blocks of data faster. This requires a dedicated server that supports the protocol, but the speed advantage is significant.
- When a Web socket is created using JavaScript, an Http request is sent to the server to initiate the connection, and when the server responds, it switches from Http to another protocol using the UPGRADE header of Http.
let socket=new WebSocket("ws://www.example.com/server.php");// No restriction on homology
socket.send("hihi");
// The server responds to the message, triggering a message that can be accessed via event.data
Copy the code