This is the 16th day of my participation in the August Text Challenge.More challenges in August

What is cross-domain

Cross-domain As we all know, different address, different port, different level, different protocol will constitute cross-domain. For example: about.haorooms.com and www.haorooms.com both constitute cross-domains. To sum up, any difference in protocol, domain name, or port is regarded as a different domain.

CORS cross-domain resource sharing

Cross-domain resource sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to allow Web applications running on one Origin (domain) to access specified resources from different source servers. When a resource requests a resource from a different domain, protocol, or port than the server on which the resource itself resides, the resource makes a cross-domain HTTP request.

Use CORS to configure both the front and back ends.

Front end: AJAX

<script type="text/javascript">
    var xhr = new XMLHttpRequest();// Ie6 uses new ActiveXObject(" microsoft.xmlhttp "); You can make a judgment of ability.
    xhr.open( "GET"."http://www.haorooms.com/CORS".true);
    xhr.send();
</script>
Copy the code

Apache: Apache requires the mod_headers module to activate the HTTP header setting, which is enabled by default. You just need to add the following to the Apache configuration file in < Directory >, < Location>, < Files > or < VirtualHost> :

Header set Access-Control-Allow-Origin *  
Copy the code

PHP: Just use the following code Settings.

<?php  
 header("Access-Control-Allow-Origin:*"); 
Copy the code

The above configuration allows requests from any domain to obtain data from the current server. Of course, there is a great risk that a malicious site could attack our server through XSS. Therefore, we should try to limit the security sources as targeted as possible, such as the following Settings so that only the domain www.haorooms.com can access the server API across the domain.

 Access-Control-Allow-Origin: http://www.haorooms.com 
Copy the code

The json cross-domain

The basic idea of JSONP is that a web page requests JSON data from the server by adding a

When data is called through a

Jsonp across domains also requires the front and back ends to work together. Usually, the back end sets a callback, and the front end passes a callback to the back end interface.

Front end:

<script type="text/javascript">
    function dosomething(jsondata){
        // Process the obtained JSON data
    }
</script>
<script src="http://haorooms.com/data.php?callback=dosomething"></script>
Copy the code

The backend:

<? php $callback = $_GET['callback'];// Get the callback function name
$data = array('a'.'b'.'c');// The data to return
echo $callback. '('.json_encode($data).')'; / / output? >Copy the code

Cross-domain via AJAX:

$.getjson ("url cross-domain address ", {parameter, callback as an argument to the back end}, function(data){// structure processing},"jsonp"); * /  
$.ajax({  
    type : "get",  
    url : "Cross-domain address",  
    dataType : "jsonp".// The data type is jsonp
    jsonp: "callback".// The function name used by the server to receive callback calls
    success : function(data){  
        // Result processing
    },  
    error:function(data){  
          console.log(data); }});Copy the code

CORS cross-domain and JSONP cross-domain advantages: COMPARED with JSONP, CORS is undoubtedly more advanced, convenient and reliable.

  1. JSONP can only implement GET requests, whereas CORS supports all types of HTTP requests.

  2. With CORS, developers can make requests and get data using plain XMLHttpRequest, which has better error handling than JSONP.

  3. JSONP is mainly supported by older browsers, which often do not support CORS, and most modern browsers already do. IE7 is not supported in earlier versions. To support IE7, use JSONP.

Webpack solves cross-domain problems

Webpack also solves front-end cross-domain problems by installing webPack’s HTTP-proxy-Middleware module

npm install http-proxy-middleware --save-dev
Copy the code

Configuration:

module.exports = {
    devtool: 'cheap-module-source-map',
    entry: './app/js/index.js'
    output: {
        path: path.resolve(__dirname, 'dev'),
        // The destination path of all output files
        filename: 'js/bundle.js',
        publicPath: '/',
        chunkFilename: '[name].chunk.js'
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'dev'),
        publicPath: '/',
        historyApiFallback: true,
        proxy: {
            / / request the request will be under the '/ device agents to target: http://debug.haorooms.com
            '/device/*': { 
                target: 'http://debug.haorooms.com',
                secure: false.// Accept services running over HTTPS
                changeOrigin: true}}}}Copy the code

Use:

 fetch('/device/space').then(res => {
        / / by proxy to http://debug.haorooms.com/device/space
        return res.json();
    }).then(res => {
        console.log(res);
    })

    fetch('device/space').then(res => {
        / / http://localhost:8080/device/space to visit a local service
        return res.json();
    }).then(res => {
        console.log(res);
    })
Copy the code

Note: The URL used must start with/or it will not be propped to the specified address.

Google Chrome cross domain Settings

Go to chrome shortcut, right-click shortcut target and add this sentence:

--disable-web-security --user-data-dir 
Copy the code