当前位置:网站首页>Resolve cross domain

Resolve cross domain

2022-06-28 04:15:00 weixin_ forty-seven million one hundred and sixty-four thousand

. Cross domain solutions

Several mainstream cross domain solutions
1.JSONP To deal with cross domain

  1. principle :
    ​ jsonp It is a means of cross domain communication , Its principle is very simple :
    ​ a: The first is to make use of script Labeled src Property to achieve cross domain .
    b: By passing the front-end method as a parameter to the server , Then the server side injects the parameters and returns , Realize the communication between the server and the client .​
    c: Due to the use script Labeled src attribute , So we only support get Method
    2. Realization way :
// establish script label 
function createScript(){
    
    // Define a script label 
   let oScript = document.createElement("script");
   //script Of src attribute   Directly assign values to the interface links that need to be cross domain 
   // And define callback Parameters , Followed by a callback function 
  oScript.src = `https://api.asilu.com/today?callback=getTodays`;
       // The generated script Added to our dom in 
       document.body.appendChild(oScript);  
  }
12345678910
	//callback Function for  
	function getTodays(data) {
    
        // Get the object data obtained across domains 
        let oTodays = data.data;
	}

​ The above is through jsonp Implements a cross domain request , Get weather data . Since it's called jsonp, Obviously, the purpose is json, And cross domain acquisition , utilize js Create a script label , hold json Of url Assign to script Of scr attribute , Put this script Insert into the page , Let the browser get resources across domains ,callback It's a callback method for page existence , Parameters are what you want json, The callback method should comply with the agreement of the server. Generally, it uses callback perhaps cb, Special note jsonp Only aim at get Formal request
3. Advantages and disadvantages
​ advantage : Easy to use , No compatibility issues .
​ shortcoming :
​ Only support GET request .
​ The front and rear ends need to be matched .
​ Because the code is loaded from other fields, the execution , So if other domains are not secure , It's likely that some malicious code will be included in the response .
2.CORS Cross-domain resource sharing (xhr2)
1. principle
​ CORS It's a W3C standard , The full name is " Cross-domain resource sharing "(Cross-origin resource sharing)- It allows the browser to cross to the source server , issue XMLHttpRequest request , To overcome AJAX A restriction that can only be used with the same origin - Whole CORS Communication process , It's all done automatically by the browser , No user involvement is required - For developers ,CORS Correspondence and homology AJAX There is no difference in communication , The code is exactly the same - Realization CORS The key to communication is the server , As long as the server realizes CORS Interface , You can communicate across sources
2. Realization
​ Realization CORS It is not difficult to , Just make some settings on the server : Such as

	//  Control the allowed request sources 
	header("Access-Control-Allow-Origin:*"); // * Indicates that any source is allowed   Basically, you can set this 
		
	// in addition , There are still some settings put request  delete Requested , There is also a custom request header ,nodejs The default is get,post
    //  Control allowed custom request headers 
    'Access-Control-Allow-Headers': 'abc,efg',
    //  Control how requests are allowed 
    'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE'

​ Be careful :IE10 The following is not supported CORS
3. Advantages and disadvantages
​ advantage :
​ CORS Correspondence and homology AJAX There is no difference in communication , The code is exactly the same , Easy to maintain .
​ Support all types HTTP request .
shortcoming
​ There are compatibility issues , especially IE10 The following browsers .
​ When a non simple request is sent for the first time, there will be one more request .
3. Server proxy cross domain
1. principle :
​ Request through the server language proxy . Such as PHP,C# The server language has no cross domain restrictions .- Let the server go to another website to get the content and then return to the page . Because the same origin policy is a security restriction for browsers . There is no cross domain problem with the server , Therefore, the server can request the resources of the desired domain and return them to the client .
​ When we request data from a third party , Through the browser ajax It must not be possible to ask , Because people won't set it for you cors, So our server proxy solution to cross domain problem arises at the historic moment .
2. Realization
I'm going through nodejs+express Implement service proxy across domains
Middleware needs to be installed http-proxy-middleware
$ npm install http-proxy-middle

 Server code 
//  Solve cross domain problems through agents 

/** *  Use nodejs Start a proxy service  *  A third party  http-proxy-middleware  middleware  */

// introduce express
const express = require('express');
// Introduce agent middleware 
const {
     createProxyMiddleware } = require('http-proxy-middleware');
// Statement express example 
const app = express();

//  Sign up for a cors Middleware , Allow cross-domain 
app.use((req, res, next) => {
    

    res.set({
    
        // Allow all domain requests , In development ,* It needs to be changed to the corresponding domain name 
        'Access-Control-Allow-Origin': '*',
        //  Set the custom request headers that the front end is allowed to pass 
        'Access-Control-Allow-Headers': 'token',
        //  Set the allowed request mode 
        'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE'
    });
	// Must write , Give control to the next 
    next();
});

//  Register a proxy middleware 
//  Front end services :http://localhost:8080
//  Agency service :http://localhost:3000
//  The target service :http://m.maoyan.com

app.use('/api', createProxyMiddleware({
    
    // configuration option 
    //  Destination address : Just the protocol and the host 
    target: "http://m.maoyan.com",
   
   /** *  The path to rewrite  * *  When we access the target interface through a proxy, the process is roughly as follows  * http://localhost:8080 ->  request  -> * http://localhost:3000/api/ajax/movieOnInfoList ->  Proxy to  -> * http://m.maoyan.com/api/ajax/movieOnInfoList *  At this time, the real target interface address does not exist  /api  This prefix is . Therefore, the request will fail  404  Other questions  * *  After setting the following path rewrite rules , The process is as follows  * http://localhost:8080 ->  request  -> * http://localhost:3000/api/ajax/movieOnInfoList ->  Proxy to  -> * http://m.maoyan.com/ajax/movieOnInfoList */
    pathRewrite: {
    
        "^/api": ""
    },
    //  Virtual hosting sites require ,  Generally, it is directly set to true Just fine 
    changeOrigin: true
}));

// monitor 3000 port , Start the service 
app.listen(3000, () => {
    
    console.log(" Agent service started successfully ");
});

 The front-end code 
 <script>
    $(function () {
    
      $.ajax({
    
        url: 'http://localhost:3000/api/ajax/movieOnInfoList',
        type: 'GET',
        success: function (res) {
    
          console.log(res)
        }
      })
    })
  </script>
原网站

版权声明
本文为[weixin_ forty-seven million one hundred and sixty-four thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/179/202206280248109429.html