当前位置:网站首页>Cross domain? Homology? Understand what is cross domain at once
Cross domain? Homology? Understand what is cross domain at once
2022-07-02 01:41:00 【Handsome BIA】
List of articles
Preface
In fact, we use ajax Data transfer , Most of the time, they are making cross domain requests , If you haven't rented a server, you may not have bothered about what this thing is . Cross domain data interaction is very common in our front and back end , But now in the era of modularity , Generally, we are not exposed to cross domain problems , Because of a lot of things API It's done for us . Next, I'll give you a good look at how cross domain is going on .
One 、 The same-origin policy
Before introducing cross domain, I think we must popularize the concept of homology strategy .
What is homology ?
If two pages of the protocol , Domain name and port are the same , The two pages have the same source .
for example , The following table shows the relative http://www.test com/index.html Page homology detection :
In order to prevent Xiaomeng Xinlian from understanding such things as the agreement domain name , Here is a brief explanation .
The agreement is on our website http Agreement or https agreement , The domain name is the name of the web address , In fact, the initial name of each server is not so recognizable , At first, our servers were like this 127.0.0.1 Name of the number , In order to make the website easy to identify , Just made it look like www.baidu.com, A recognizable name . Ports are easy , Is the interface of the server .
Back to the point
What is homology strategy ?
The same-origin policy ( English full name Same origin policy) It is a security function provided by the browser .
MDN Officially given concept : The same origin policy restricts how documents or scripts loaded from the same source interact with resources from another source . This is an important security mechanism for isolating potentially malicious files .
To put it bluntly, browser rules ,A Website JavaScript, Not allowed with non homologous sites C Between , Interact with resources , for example :
① Can't read non homologous pages Cookie、LocalStorage and IndexedDB
② No access to non homologous web pages DOM
③ Can't send... To a non homologous address Ajax request
Two 、 Cross domain
1. What is cross-domain ?
Homology refers to two URL The agreement 、 domain name 、 Port consistency , conversely , It's cross domain .
The root cause of cross domain : The browser's homology policy does not allow non homology URL Interact with resources .
For example, the following two domain names are different , Then the data interaction between them belongs to cross domain
Webpage : http://www.test.com/index.html
Interface : http://www.api.com/userlist
2. How does the browser block cross domain ?
A picture is worth a thousand words
To put it bluntly, the browser allows cross domain requests , however , Data returned from cross domain requests , Will be blocked by the browser , Unable to get... By the page .
3. How to implement cross domain data requests ?
There are many ways to solve cross domain requests , Let me first introduce the two main solutions , Namely JSONP and CORS.
JSONP: It's early , Compatibility is good. ( Compatible with lower versions IE). It's the front-end programmer to solve cross domain problems , Forced to come up with a temporary solution . The disadvantage is that it only supports GET request , I won't support it POST request .
CORS: Late appearance , It is W3C standard , Cross domain Ajax The underlying solution to the request . Support GET and POST request . The disadvantage is that it is not compatible with some lower versions of browsers .
3、 ... and 、JSONP
1.JSONP What is it? ?
JSONP (JSON with Padding) yes JSON A kind of " Usage mode ”, It can be used to solve the problem of cross-domain data access in major browsers .
2.JSONP Implementation principle of
Due to the restriction of browser homology strategy , Can't pass... In the web page Ajax Request non homologous interface data . But because of <script>
Tags are not affected by browser homology policy , Can pass src attribute , Request non homologous js Script .
To put it bluntly ,JSONP Implementation principle of , It is through <script>
Labeled src attribute , Request a cross domain data interface , And in the form of function calls , Receive the data returned from the cross domain interface response .
therefore JSONP In fact, the principle of "Tao WA" has a little meaning , To use the callback function to " Cheated " browser .
3.Jquery Provided JSONP Interface
jQuery Provided ajax() function , In addition to initiating real Ajax In addition to data requests , Can also initiate JSONP Data request . Usage and ajax almost .
for example :
$.ajax({
url :'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age= 20',
// If you want to use $.ajax() launch JSONP request , Must specify datatype by jsonp
dataType:'jsonp',
success: function(res) {
console. log (res)
})
By default , Use JQuery launch JSONP request , Will automatically carry a callback=jQueryxx Parameters of ,JQueryxxx Is the name of a randomly generated callback function .
jQuery Medium JSONP, through <script>
Labeled src Property to achieve cross domain data access , It's just , JQuery It adopts dynamic creation and removal <script>
How to label , To dial up JSONP Data request .
● Is initiating JSONP On request , Dynamic direction <header>
in append One <script>
label ;
● stay JSONP After the request is successful , Dynamic from <header>
Remove just append In the <script>
label ;
Four 、CORS
CORS In fact, it is cross domain 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 .
1、 Common cross domain request : Just set up on the server side Access-Control-Allow-Origin
2、 belt cookie Cross-domain request : Both front and rear ends need to be set
front end JQuery.axjax Set up , according to xhr.withCredentials Field to determine whether there is cookie
$.ajax({
url: 'http://ajax.frontend.itheima.net:3006',
type: 'get',
data: {
},
xhrFields: {
withCredentials: true // The front end is set with or without tape cookie
},
crossDomain: true, // Will make the request header contain additional information across domains , But it doesn't include cookie
});
CORS Requires both browser and server support . at present , All browsers support this feature ,IE The browser cannot be lower than IE10. Whole CORS Communication process , It's all done automatically by the browser , No user involvement is required . For developers ,CORS Correspondence and homology AJAX signal communication There is no difference , The code is exactly the same . Once the browser finds AJAX Request cross source , Will automatically add some additional header information , Sometimes there will be one more attachment My request , But users don't feel . therefore , Realization CORS The key to communication is the server . As long as the server implements it CORS Interface , You can communicate across sources .
So many times we use ajax Reasons for making cross domain requests without realizing , That is, the back-end server has been used CORS The interface is ready for cross source communication .
CORS Manual processing method :
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method' )
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, PUT, DELETE')
res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
next();
});
Use cors package ( encapsulation ):
npm install cors --save-dev
const cors = require('cors');
app.use(cors());
What we need to pay attention to here is the setting Origin There are two kinds of situations in field :* And a domain name
In the use of *( Accept all domain names ) For security reasons, the browser will not send Cookie It's worth it , It's OK to use a domain name . But in actual development, we usually only need to use a domain name to complete the business .
summary
There are many cross domain methods , For example, use nginx perhaps websocket, image CORS Different backend codes are written differently , Bloggers have not fully mastered , Other content will continue to be updated in the future .
边栏推荐
- Self drawing of menu items and CListBox items
- Study note 2 -- definition and value of high-precision map
- [IVX junior engineer training course 10 papers to get certificates] 0708 news page production
- Makefile simple induction
- Convolutional neural network (including code and corresponding diagram)
- Leetcode 45 Jumping game II (2022.02.14)
- 【图像增强】基于Frangi滤波器实现血管图像增强附matlab代码
- Brief description of grafana of # yyds dry goods inventory # Prometheus
- Exclusive delivery of secret script move disassembly (the first time)
- 1218 square or round
猜你喜欢
学习笔记2--高精度地图定义及价值
电商系统中常见的9大坑,你踩过没?
Private project practice sharing [Yugong series] February 2022 U3D full stack class 009 unity object creation
Introduction to ffmpeg Lib
Unity AssetBundle subcontracting
[rust web rokcet Series 1] Hello, world and get, post, put, delete
[IVX junior engineer training course 10 papers] 06 database and services
Réseau neuronal convolutif (y compris le Code et l'illustration correspondante)
基于SSM实现微博系统
6-2 vulnerability exploitation - inevitable problems of FTP
随机推荐
【LeetCode 43】236. The nearest common ancestor of binary tree
matlab 实现语音信号重采样和归一化,并播放比对效果
浅浅了解Servlet
Day 13 of hcip (relevant contents of BGP agreement)
We should make clear the branch prediction
站在新的角度来看待产业互联网,并且去寻求产业互联网的正确方式和方法
微信小程序中使用tabBar
Six lessons to be learned for the successful implementation of edge coding
[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production
Android: how can golden nine and silver ten squeeze into the first-line big factories from small and medium-sized enterprises? The depth of interview questions in large factories
Learn basic K-line diagram knowledge in three minutes
Bat Android Engineer interview process analysis + restore the most authentic and complete first-line company interview questions
遊戲思考15:全區全服和分區分服的思考
Edge extraction edges based on Halcon learning_ image. Hdev routine
6-3漏洞利用-SSH环境搭建
Using tabbar in wechat applet
Learning note 24 - multi sensor post fusion technology
The technology boss is ready, and the topic of position C is up to you
Single chip microcomputer -- hlk-w801 transplant NES simulator (III)
并发编程的三大核心问题