In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "cross-domain example analysis of WEB front-end", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and learn the article "WEB front-end cross-domain example analysis".
WEB front-end cross-domain solution
Cross-domain definition
Broad definition: cross-domain refers to a document or script under one domain trying to request resources under another domain.
1. Resource jump: link, redirect, form submission
2. Resource embedding:,
, and other dom tags, as well as the outer chain of files such as background:url () and @ font-face () in the style
3. Script requests: ajax requests initiated by js, cross-domain operations of dom and js objects, etc.
Homologous strategy
Homologous policy / SOP (Same origin policy) is a kind of convention, which was introduced by Netscape company in 1995. It is the core and basic security function of browser. Without homologous policy, browsers are vulnerable to XSS, CSFR and other attacks. The so-called homology means that "protocol + domain name + port" is the same, even if two different domain names point to the same ip address, they are not of the same origin.
The same origin policy restricts the following behaviors:
1. Cookie, LocalStorage and IndexDB cannot be read
2. DOM and Js objects cannot be obtained
3. AJAX request cannot be sent
Cross-domain solution
1) jsonp cross-domain
Grasp a few points about the principle of jsonp:
1. The src attribute of the html tag has no homology restriction (cross-domain is supported). When the browser parses the script tag, it automatically downloads the resource pointed to by the src attribute value (url).
2. After the resource file pointed to by the script tag is downloaded, the contents of it will be executed immediately
3. The server-side program parses the parameters passed by url in the src attribute value, and returns one or more function call expressions based on these parameters. The parameters of these function call expressions are the data that the client wants across domains.
4. In the file generated and returned by the server, the function called by the expression has been defined locally in advance, and the parameter is the data you want to get from the cross-domain server. Literal script tags can be used, or script can be dynamically added to the dom tree, which makes it easier to bind events.
5. Only get can be realized, which is also his weakness
Achieve:
/ / the server returns: test ({code: 0, message: "success",}); var script = document.createElement ("script"); script.type = "text/javascript"; / / pass parameters and specify the callback execution function as callback script.src = "http://www.chuchur.com/login?callback=test"; document.head.appendChild (script); / / callback execution function function test (res) {console.log (JSON.stringify (res)) } / / jquery ajax:$.ajax ({url: "http://www.chuchur.com/login", type:" get ", dataType:" jsonp ", / / request method is jsonp jsonpCallback:" test ", / / Custom callback function name data: {},}) / / vue.jsthis.$http .jsonp ("http://www.chuchur.com/login", {params: {}, jsonp:" test ",}) .then ((res) = > {console.log (res);})
2) document.domain + iframe cross-domain
Principle: this scheme is limited to the same main domain, different sub-domain, the principle is that two pages through js forced to set window.domain as the main domain, so as to achieve the same domain.
Achieve:
Document.domain = "chuchur.com"; var user = "chuchur"; document.domain = "chuchur.com"; / / get the variable alert in the parent window ("get data from the parent window" + window.parent.user)
3) location.hash + iframe cross-domain
Principle: the principle is to pass the value through URL, and then monitor the change of its hash value, then make a springboard through the middle layer, and then use the parent-child window js parent to access all page objects in the same domain.
Domain 1: a.html, domain 2:b.html, domain 1:c.html.
A.htmldirection b.html different domains can only be communicated through hash.
B.html.c.html is not in the same domain and can only communicate individually.
A.html.c.html is in the same domain, so c.html can access a.html page objects through parent
Achieve:
1. A.html: (www.chuchur.com/a.html)
Var iframe = document.getElementById ("iframe"); / pass the hash value setTimeout to b.html (function () {iframe.src = iframe.src + "# nick=chuchur";}, 1000); / / Open to the callback method function test (res) of the same domain c.html {alert ("data comes from c.html-- >" + res);} `
2. B.html: (www.chuchur.org/b.html)
Var iframe = document.getElementById ("iframe"); / / listen for the hash value from a.html, and then pass it to c.html _ window.onhashchange = function () {iframe.src = iframe.src + location.hash;}
3. C.html: (www.chuchur.com/c.html)
/ / listen for the hash value from b.html _ window.onhashchange = function () {/ / then pass the result back to window.parent.parent.test ("Hello:" + location.hash.replace ("# nick=", ")) by operating the js callback of a.html in the same domain;}
4) window.name + iframe cross-domain
Principle: using window.name-specific properties, name values still exist on different pages or even different domains when the page is reloaded, and support very long values, about 2MB.
Achieve:
/ / 1.) a.html: (www.chuchur.com/a.html) var proxy = function (url, callback) {var state = 0; var iframe = document.createElement ("iframe"); / / load the cross-domain page and let the name of the page perform the assignment, iframe.src = url / / the onload event will be triggered twice to load the cross-domain page for the first time and retain the data after window.name iframe.onload = function () {if (state = 1) {/ / the second onload (same domain proxy page) succeeds, and reads the data test (iframe.contentWindow.name) in the same domain window.name; destoryFrame () } else if (state = 0) {/ / after the first onload (cross-domain page) is successful, switch to the same domain agent page iframe.content_Window.location = "http://www.chuchur.com/b.html"; state = 1;}; document.body.appendChild (iframe); / / destroy the iframe and free memory after obtaining the data This also ensures security (not accessed by other domain frame js) function destoryFrame () {iframe.contentWindow.[ XSS _ clean] ("); iframe.contentWindow.close (); document.body.removeChild (iframe);}}; / / request cross-domain b-page data proxy (" http://www.domain2.com/b.html", function (data) {alert (data);})) / / 2.) proxy.html: (www.chuchur.com/proxy.html), this page can write nothing, but be sure to access window.name properly = "I am a variable that can be very long"
5) postMessage cross-domain
PostMessage is the API in HTML5 XMLHttpRequest Level 2 and can solve the following problems:
A.) data transfer between the page and the new window it opens
B.) message passing between multiple windows
C.) Page and nested iframe messaging
D.) Cross-domain data transfer usage for the above three scenarios: the postMessage (data, origin) method accepts two parameters
The data:html5 specification supports any basic type or replicable object, but some browsers only support strings, so it's best to use JSON.stringify () serialization when passing parameters.
Origin: protocol + host + port number, can also be set to "\ *", indicating that it can be passed to any window, or set to "/" if you want to specify the same origin as the current window.
Achieve:
Var iframe = document.getElementById ("iframe"); iframe.onload = function () {var data = {name: "Qiu Qiu",}; / / transfer cross-domain data iframe.contentWindow.postMessage (JSON.stringify (data), "http://www.chuchur.org");} to chuchur.org / / accept chuchur.org return data window.addEventListener ("message", function (e) {alert ("I'm from chuchur.org:" + e.data);}, false); / / receive chuchur.com data window.addEventListener ("message", function (e) {alert ("I'm from chuchur.com" + e.data); var data = JSON.parse (e.data) If (data) {data.nick = chuchur; / / and then send back to chuchur.com window.parent.postMessage (JSON.stringify (data), "http://www.chuchur.org");}}, false)
6) Cross-domain resource sharing (CORS)
Principle: ordinary cross-domain request: only the server can set Access-Control-Allow-Origin, and the frontend does not need to be set.
With cookie request: both frontend and backend need to set fields. Note that the cookie is the cookie of the domain where the cross-domain request API resides, not the current page. Currently, all browsers support this feature (IE8+:IE8/9 requires the use of XDomainRequest objects to support CORS), and CORS has become a mainstream cross-domain solution.
Achieve:
/ / 1) Native jsvar xhr = new XMLHttpRequest (); / / window is required for IE8/9. XDomainRequest compatible / / with cookiexhr.withCredentials = true;xhr.open ('post',' http://www.chuchur.com/login', true); xhr.setRequestHeader ('Content-Type',' application/x-www-form-urlencoded'); xhr.send ('user=chuchur'); xhr.onreadystatechange = function () {if (xhr.readyState = = 4 & & xhr.status = = 200) {alert (xhr.responseText);}} / 2.) jQuery ajax$.ajax ({. XhrFields: {withCredentials: true// frontend setting with cookie}, crossDomain: true, / / will make the request header contain additional cross-domain information, but not cookie.}); / / 3.) vue framework adds the following code to the ajax component encapsulated by vue-resource: Vue.http.options.credentials = true// backend server / / java/* * import package: import javax.servlet.http. Defined in the HttpServletResponse; * API parameters: HttpServletResponse response * / response.setHeader ("Access-Control-Allow-Origin", "http://www.chuchur.com"); / / if you have a port, you need to write full (protocol + domain name + port) response.setHeader (" Access-Control-Allow-Credentials "," true "); / / nodevar server = http.createServer (); server.on ('request', function (req, res) {var postData ='') / / data block receiving req.addListener ('data', function (chunk) {postData + = chunk;}); / / data receiving completed req.addListener (' end', function () {postData = qs.parse (postData)) / / the cross-domain backend sets res.writeHead (200,{ 'Access-Control-Allow-Credentials':' true', / / the backend is allowed to send Cookie' Access-Control-Allow-Origin': 'http://www.chuchur.com', / / allowed access to the domain (protocol + domain name + port)' Set-Cookie': 'domain abcdefs; Path=/; Domain=www.chuchur.com HttpOnly' / / HttpOnly: script cannot read cookie}); res.write (JSON.stringify (postData)); res.end ();}); server.listen ('3000')
7) nginx reverse proxy cross-domain
Cross-domain access to general static resources such as js, css and img by browsers is permitted by the same origin policy, with the exception of iconfont font files (eot | otf | ttf | woff | svg). The following configuration can be added to the static resource server of nginx.
Location / {add_header Access-Control-Allow-Origin *;}
Principle: use nginx to proxy a springboard with different ports in the same domain, and reverse proxy to cross-domain domain name, so that you can modify the domain information in cookie to achieve cross-domain.
Achieve:
# nginx configuration: server {listen 80; server_name www.chuchur.com; location / {proxy_pass http://www.chuchur.org; # reverse proxy proxy_cookie_domain www.chuchur.org www.chuchur.com; # modify the domain name index index.html index.htm in cookie # when using webpack-dev-server and other middleware proxy interfaces to access nignx, there is no browser participation, so there is no homology restriction. The following cross-domain configuration does not enable add_header Access-Control-Allow-Origin http://www.chuchur.com; # when the current end only cross-domain without cookie, it can be * add_header Access-Control-Allow-Credentials true;}}
Front-end implementation
Var xhr = new XMLHttpRequest (); / / Front switch: whether the browser reads and writes cookiexhr.withCredentials = true;// accesses the proxy server xhr.open ('get',' http://www.chuchur.com/?user=chuchur', true) in nginx; xhr.send (); / / nodevar http = require ('http') Var server = http.createServer (); var qs = require ('querystring'); server.on (' request', function (req, res) {var params = qs.parse (req.url.substring (2)); / / write cookie res.writeHead to the foreground (200,{ 'Set-Cookie': 'lroomabcdefs; Path=/; Domain=www.chuchur.org; HttpOnly' / / HttpOnly: the script cannot be read}); res.write (JSON.stringify (params)); res.end ();}) Server.listen ('8080')
8) Nodejs middleware agent cross-domain
The principle is similar to the cross-domain principle of the nignx proxy, which forwards data through the proxy server.
Achieve:
/ / 1) using middleware http-proxy-middleware to implement var express = require ('express'); var proxy = require (' http-proxy-middleware'); var app = express () App.use ('/', proxy ({/ / proxy cross-domain target interface target: 'http://www.chuchur.org:', changeOrigin: true, / / modify response header information to achieve cross-domain and allow cookie onProxyRes: function (proxyRes, req, res) {res.header (' Access-Control-Allow-Origin', 'http://www.chuchur.com'); res.header (' Access-Control-Allow-Credentials', 'true')) }, / / modify the cookie domain name cookieDomainRewrite in the response information: 'www.chuchur.com' / / can be false, which means no modification}); app.listen (3000); / / 2) use middleware webpack-dev-server to implement / / webpack.config.js partial configuration: module.exports = {entry: {}, module: {},... DevServer: {historyApiFallback: true, proxy: [{context:'/ login', target: 'http://www.chuchur.org', / / proxy cross-domain target interface changeOrigin: true, cookieDomainRewrite:' www.chuchur.com' / / can be false, which means no modification}], noInfo: true}}
9) WebSocket protocol cross-domain
WebSocket protocol is a new protocol of HTML5. It realizes full-duplex communication between browser and server, and allows cross-domain communication at the same time. It is a good implementation of server push technology. Native WebSocket API is not very convenient to use, we use Socket.io, which well encapsulates the webSocket interface, provides a simpler and flexible interface, and provides backward compatibility for browsers that do not support webSocket.
Achieve:
1. Front-end code
User input: var socket = io ("http://www.chuchur.org"); / / connection successfully processed socket.on (" connect ", function () {/ / listen for server message socket.on (" message ", function (msg) {console.log (" message from server: "+ msg);})) / / the listening server closes socket.on ("disconnect", function () {console.log ("Server socket has closed.");}); document.getElementsByTagName ("input") [0] .onblur = function () {socket.send (this.value);}
2. Nodejs socket backend:
Var http = require ('http'); var socket = require (' socket.io'); / / start http service var server = http.createServer (function (req, res) {res.writeHead (200,{ 'Content-type':' text/html'}); res.end ();}); server.listen ('8080'); console.log (' Server is running at port 8080. '); / / listen for socket connection socket.listen (server) .on (' connection', function (client) {/ / receive message client.on ('message', function (msg) {client.send (' :'+ msg); console.log ('message from customer server':-- >'+ msg);}) / / disconnect processing client.on ('disconnect', function () {console.log (' Client socket has closed.');});})
The above nine methods can achieve cross-domain data transmission, and the sixth cross-domain resource sharing (CORS) is the most commonly used, and the separated development mode is the most common in the front and back end. The seventh and eighth middleware proxy implementations are commonly used in node-based development.
Among them, the second, third, fourth and fifth schemes can realize the data communication between different windows by using ifame and postMessage.
The above is all the content of the article "Cross-domain sample Analysis of WEB Front end". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.