Great front-end cross-domain solutions

Foreword

What is cross-domain
popular thing in terms of cross-domain refers to a document or script in a field trying to request additional resources under a domain, thus creating a cross-domain,

域: Refers to a form of computer network, the use of computers in the domain that everyone will receive a unique user account, you can then access the resources allocated for the domain account.

Common cross-domain scenario
as a front-end, cross-domain we most often encounter is the browser should request cross-domain resource, a bit more professional terms is limited by the browser's same-origin policy;
the so-called homologous means "protocol + domain name + port, "the same three, even two different domain names point to the same ip address, nor homologs.

协议:http/https             域名www.HiSen.com             端口:8080     

URL                                说明                    是否允许通信  
http://www.HiSen.com
http://www.HiSen.com         同一域名                         允许

http://www.HiSen.com:8080
http://www.HiSen.com:8081    同一域名,不同端口                不允许
 
http://www.HiSen.com
https://www.HiSen.com        同一域名,不同协议                不允许
 
http://www.HiSen.com
http://192.168.1.37          域名和域名对应相同ip              不允许
 
http://www.HiSen1.com
http://www.HiSen2.com        不同域名                         不允许

How to solve

Jsonp
Speaking jsonplikely everyone Tucao, more soil, the current mainstream framework vue reactterms may have little use ajaxfor network requests, over here, we do share a simple, in my understanding, jsonpin fact, the definition of front-end a global server callback function to be executed, the callback function parameter is the return value of the request; we come to know about through the code:

By requesting a front-end data, through a getrequest to simply practice it.

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

    // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
    script.src = 'http://www.HiSen.com:8080/getData?callback=callbackFun';
    document.head.appendChild(script);

    // 定义全局回调函数
    function callbackFun(res) {
        alert(JSON.stringify(res));
    }
 </script>

We backend through a simple nodelook at the service point of view.

var http = require('http');
var url = require('url');
var server = http.createServer();
server.on('request', function(req, res) {
	//获取get请求参数
    var params = qs.parse(req.url.split('?')[1]);
    //获取callback函数名称
    var fn = params.callback;

    // jsonp返回设置
    res.writeHead(200, { 'Content-Type': 'text/javascript' });
    // 返回一个全局函数被执行 - 也就是页面上定义的全局回调函数
    res.write(fn + '(' + JSON.stringify(params) + ')');

    res.end();
});

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

Through this example of the top, if we all understand it? In fact, return to a global callback function, parameter is the value we have to be returned by the server. Of course, this is by native Js to interpret, others we do not have to worry about, are all treated;
ajaxonly need to set dataType:jsonp, and set jsonpCallback:回调函数名称to,
vuebut also set the corresponding jsonp: 回调函数名称
disadvantages of self-evident, JSONPcan only GETrequest.

cors
cross-domain resource sharing, this is perhaps the most used small partners solutions, and usually work are also set by the server Access-Control-Allow-Origincan be, simple, fast; CORS has become the mainstream of cross-domain solutions.
Ordinary cross-domain requests: only the server settings Access-Control-Allow-Origin can, with a cookie request to: the front and rear ends need to be set.

About vueframework, everyone is currently using more axios 和 vue-resource, then they need to do two simple set about:

//axios设置:
axios.defaults.withCredentials = true

//vue-resource设置:
Vue.http.options.credentials = true

Check the server how to set your own Access-Control-Allow-Originproperty, I will not get nodeto do a sample.

node middleware agent

In fact, when it comes to nodemiddleware, it is to start a proxy server, for data forwarding, disguised croscross-domain resource sharing in nodethere to set some properties return headAccess-Control-Allow-Origin

Take expressframework for:

var express = require('express');
var app = express();
app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    next();
}

WebSockt protocol
web sockets is a browser API, long two-way communication connection. (Same origin policy does not apply to web sockets)

web sockets Principle: After JS created a web socket, there will be a HTTP request is sent to the browser to initiate a connection. After obtaining the server responds, the connection will replace the http protocol established web sockt agreement.

var socket = new WebSockt('ws://www.HiSen.com');//http -> ws; https -> wss
socket.send('WebSockt 连接');
socket.onmessage = function(event){
    var data = event.data; // 回调
}

Of course, there are some students might be when it comes to the current webpackvariety of configurations, such vue have proxyagents and so on. It is also a solution.

Published 20 original articles · won praise 40 · views 5864

Guess you like

Origin blog.csdn.net/HiSen_CSDN/article/details/103654974