Cross-domain problems and solutions

Approximate process of client request service

Insert picture description here

Cross-domain request

Insert picture description here

Same-origin group policy: (Same-source: same protocol, same domain name (host), same port) The Ajax request address and the address of the current page must be the same protocol, same domain name, and same port, so that Ajax requests can be sent normally. If any of the three is different, it is determined that the request is a cross-domain request, and the browser will block the request and report an error in the console.

Cross-domain solutions: CORS, server reverse proxy, JSONP, ajax.

Ajax solves cross-domain problems: (node ​​solves cross-domain problems: server reverse proxy)

	server.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");
	    if (req.method.toLowerCase() == 'options')
	        res.send(200);  //让options尝试请求快速结束
	    else
	        next();
	})

JSONP principle: a technology to solve cross-domain problems, does not depend on the real network environment. Ajax requests are affected by the same-origin policy and cross-domain requests are not allowed, but the link in the src attribute of the script tag can access cross-domain js scripts. With this feature, the server no longer returns data in JSON format, but returns a paragraph The js code that calls a function is called in the src, thus achieving cross-domain.

JOSNP working mechanism: dynamically create a script tag, and set its src attribute to send an http request to the server, and declare a callback function in advance. The function name of the callback function is passed to the backend using the callback request parameter, and the backend receives After the front-end request, obtain the request parameters of the callback request and splice a JS code segment that calls the function, and the data to be returned to the front-end exists in the form of actual parameters. After the front-end receives the response from the back-end, it will return the content of the back-end Execute as JS code, that is, call a function and use a formal parameter to receive the data to be passed by the backend.

let oBody=document.querySelector("body");
function fn(data){
    
    
    console.log(data);//输出后端返回的数据
}

 // 动态创建script
 let script = document.createElement("script");
//向后端发送请求
script.setAttribute("src","请求路径?callback=fn&...");
// 将script插入到body后面
oBody.appendChild(script);

Guess you like

Origin blog.csdn.net/yanyuyanyan/article/details/112364930