preface

Cross domain can be said to be a very common problem in the front end, encounter a variety of scenarios, today we will take a look at what cross domain is. How do you figure this thing out

What is cross-domain

In plain English, cross-domain is when a document or script in one domain tries to request a resource in another domain.

Domain: A form of computer network in which each person using a computer in a domain receives a unique user account that can then be assigned access to resources within that domain.

Common cross-domain scenarios

As a front-end, we most often encounter cross-domain should be the browser request resources cross-domain, professionally speaking, is limited by the same origin policy of the browser; Same-origin means that the protocol, domain name, and port are the same. Even if two different domain names point to the same IP address, they are not same-origin.

Protocol: HTTP/HTTPS Domain name www.HiSen.com Port:8080URL indicates whether communication is allowedhttp://www.HiSen.com
http://www.HiSen.com Same domain name allowed

http://www.HiSen.com:8080
http://www.HiSen.com:8081 Do not allow different ports for the same domain name
 
http://www.HiSen.com
https://www.HiSen.com Same domain name, different protocols do not allow
 
http://www.HiSen.com
http://192.168.1.37 The domain name cannot correspond to the same IP address
 
http://www.HiSen1.com
http://www.HiSen2.com different domain names are not allowed
Copy the code

How to solve

Jsonp

When it comes to JSONP, we may make a joke of it. In terms of the mainstream framework vue React, we may rarely use Ajax to make network requests. In my understanding, JSONP actually defines a global callback function to be executed by the server. The argument to the callback function is the request return value; Let’s look at the code:

The front end simply does this by requesting a piece of data, with a GET request.

<script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // Pass the name of a callback function to the back end, so that the back end can execute the callback function defined in the front end when it returns
    script.src = 'http://www.HiSen.com:8080/getData?callback=callbackFun';
    document.head.appendChild(script);

    // Define the global callback function
    function callbackFun(res) {
        alert(JSON.stringify(res));
    }
 </script>
Copy the code

Let’s look at the back end with a simple Node service.

var http = require('http');
var url = require('url');
var server = http.createServer();
server.on('request'.function(req, res) {
	// Get the get request parameters
    var params = qs.parse(req.url.split('? ') [1]);
    // Get the callback function name
    var fn = params.callback;

    // jsonp returns Settings
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    // Returns a global function to be executed - that is, the global callback defined on the page
    res.write(fn + '(' + JSON.stringify(params) + ') ');

    res.end();
});

server.listen('8080');
console.log('Server is running at port 8080... ');
Copy the code

Does the example above make sense to everyone? The server returns a global callback that takes the value we want to return. Of course, this is interpreted by native Js, others do not worry, are processed; Ajax only needs to set dataType: jSONp and set the jsonpCallback function name. Vue also has the corresponding setting jSONp: callback function name.

cors

Cross-domain resource sharing, this may be the most used solution for friends, usually work is also through the server to set access-Control-allow-Origin can be simple, fast; CORS has also become a mainstream cross-domain solution. For common cross-domain requests, only access-Control-allow-origin needs to be set on the server. To send requests with cookies, both the front and back ends need to be set.

The most common vUE frameworks are Axios and VUe-Resource, both of which require a simple setup:

/ / axios Settings:
axios.defaults.withCredentials = true

/ / the vue - resource Settings:
Vue.http.options.credentials = true
Copy the code

Check out the access-Control-allow-Origin attribute on the server, so I won’t use Node as an example.

Node middleware Proxy

Actually speaking of node middleware, it is to start a proxy server, do data forwarding, a variant of Cros cross-domain resource sharing, set some return header attribute access-Control-Allow-Origin in node

Take the Express framework:

var express = require('express');
var app = express();
app.all("*".function(req,res,next){
    * indicates that any domain name is allowed to cross domains
    res.header("Access-Control-Allow-Origin"."*");
    // The allowed header type
    res.header("Access-Control-Allow-Headers"."content-type");
    // The type of requests that are allowed across domains
    res.header("Access-Control-Allow-Methods"."DELETE,PUT,POST,GET,OPTIONS");
    next();
}
Copy the code

WebSockt agreement

Web Sockets are a browser API, long connection bidirectional communication. (Same-origin policy does not apply to Web Sockets)

Web Sockets Principle: After JS creates the Web socket, an HTTP request is sent to the browser to initiate the connection. After the server responds, the established connection replaces the HTTP protocol with the Web SOCKT protocol.

var socket = new WebSockt('ws://www.HiSen.com');//http -> ws; https -> wss
socket.send('WebSockt connection');
socket.onmessage = function(event){
    var data = event.data; / / callback
}
Copy the code

Of course, some students may mention that webpack has various configurations, such as vUE has proxy proxy and so on. It’s also a solution.