当前位置:网站首页>Web development solution to cross domain problems
Web development solution to cross domain problems
2022-06-25 18:36:00 【ookaoooo】
What is cross domain access
stay A In the website , We want to use Ajax To obtain a B Specific content in a website . If A Website and B The site is not in the same domain , Then cross domain access problem appears . You can understand that two domain names cannot send requests or request data across the domain name , Otherwise it's not safe . Cross domain access violates the same origin policy , The homology policy stipulates that , Browser's ajax You can only access the HTML Resources of page homology .

Head key settings Head key settings Head key settings ( Say important things three times )
The first setting item ( a key : Whether he can visit or not is his reason ):Access-Control-Allow-Origin
The response header can carry a Access-Control-Allow-Origin Field , The syntax is as follows :
Access-Control-Allow-Origin: <origin> | *among ,origin The value of the parameter specifies the foreign domain that is allowed to access the resource URI. For requests that do not need to carry identity credentials , The server can specify that the value of this field is a wildcard , Indicates that requests from all domains are allowed .
for example , The following field values will be allowed to come from http://AABB.com Is a cross-domain request :
Access-Control-Allow-Origin: http://AABB.comThe following field values will allow cross domain requests from all addresses :
Access-Control-Allow-Origin: *If the server specifies a specific domain name instead of “*”, So in response to the header Vary The value of the field must contain Origin. This will tell the client : The server returns different content to different origin sites .
The second setting item ( a key : The relevant settings for access should be set by the client 、 The server should be consistent , Particular attention Content-Type, Submit data type JSON、 object 、 Or arrays, etc ):Access-Control-Expose-Headers
When accessing across domains ,XMLHttpRequest object (AJAX In fact, this method is used to submit data ) Of getResponseHeader() Method can only get some basic response headers ,Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma, If you want to visit other headers , The server is required to set the response header .
[Access-Control-Expose-Headers] The header lets the server put the header that the browser is allowed to access into the white list , for example :
Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header So the browser can go through getResponseHeader visit X-My-Custom-Header and X-Another-Custom-Header Response header .
The third setting item ( Non emphasis )Access-Control-Max-Age
[Access-Control-Max-Age] The head designated preflight How long can the requested results be cached , Please refer to the above mentioned in this article preflight Example .
Access-Control-Max-Age: <delta-seconds>delta-seconds parameter preflight How many seconds is the result of the request valid .
The fourth setting item ( Non emphasis , Take a look when there is a problem with the server configuration ) Access-Control-Allow-Credentials
[Access-Control-Allow-Credentials] The header specifies the browser credentials Set to true Whether to allow browser to read response The content of . When used on preflight Pre detect the response of the request , It specifies whether the actual request can be used credentials. Please note that : Simple GET The request will not be pre checked ; If this field is not included in the response to such a request , This response will be ignored , And the browser will not return the corresponding content to the web page .
Access-Control-Allow-Credentials: trueThe fifth setting item ( a key : How to submit data ) Access-Control-Allow-Methods
[Access-Control-Allow-Methods] The header field is used for the response to the preview request . It indicates what... The actual request allows HTTP Method .
Access-Control-Allow-Methods: <method>[, <method>]*Access-Control-Allow-Headers
Access-Control-Allow-Headers The header field is used for the response to the preview request . It indicates the first field allowed in the actual request .
Access-Control-Allow-Headers: <field-name>[, <field-name>]*There are three ways to solve cross domain problems
- Cross domain becomes the same domain !( Put the requested page and the requested address in the same domain name or IP Run under address )
- Server configuration cross domain ( For setting items, refer to the setting options mentioned above )Apache The server
<IfModule mod_headers.c>
<FilesMatch "\.(svg|ttf|otf|eot|woff|woff2)$">
Header set Access-Control-Allow-Origin "*" // Set item All address domain names can obtain resources of this server across domains
</FilesMatch>
</IfModule>Nginx
location ~* \.(eot|ttf|woff)$ {
add_header Access-Control-Allow-Origin '*';
}IIS
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>3. The server cannot be changed ( Change the backend project code , I use it here. PHP explain , For others, you can check the manuals of your corresponding back-end languages )
<?php
header('content-type:application:json;charset=utf8'); // receive JSON
header('Access-Control-Allow-Origin:*');// All domain addresses
header('Access-Control-Allow-Methods:POST');//post Mode submission
header('Access-Control-Allow-Headers:x-requested-with,content-type');
?>in other words After the backend is defined like this , The front end should also submit data in this way ! Use POST data Turn into JSON, So the back end can get the data , And deal with , Then return Data to the front end is also JSON The data of !
It is also a program Xiaobai , If there is something wrong, the great God will give you some advice !
边栏推荐
- 网络安全检测与防范 测试题(四)
- 利尔达蓝牙空调接收器方案助力打造更舒适的公路生活
- Analysis on policy, output and market scale of China's natural gas hydrogen production industry in 2020 [figure]
- [deeply understand tcapulusdb technology] table management of document acceptance
- 158 Bar _ Modèle Power bi utilise Dax + SVG pour créer des diagrammes d'affaires presque toutes les possibilités
- 使用宝塔来进行MQTT服务器搭建
- TCP/IP 测试题(四)
- Basic operation details of binary search tree (BST) (complete code, including test cases)
- Sword finger offer double pointer
- connect to address IP: No route to host
猜你喜欢

【深入理解TcaplusDB技术】单据受理之事务执行

一晚上做了一个xpath终结者:xpath-helper-plus

【深入理解TcaplusDB技术】TcaplusDB业务数据备份
![Overview and trend analysis of China's foreign direct investment industry in 2020 [figure]](/img/b3/73e01601885eddcd05b68a20f83ca8.jpg)
Overview and trend analysis of China's foreign direct investment industry in 2020 [figure]

Hash of redis command
![[deeply understand tcapulusdb technology] table management of document acceptance](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[deeply understand tcapulusdb technology] table management of document acceptance

使用宝塔来进行MQTT服务器搭建

Redis configuration (Internet access, password)

【ELT.ZIP】OpenHarmony啃论文俱乐部—数据密集型应用内存压缩

Dell R530内置热备盘状态变化说明
随机推荐
初探Oracle全栈虚拟机---GraalVM
Kwai 616 war report was launched, and the essence was thrown away for the second time to lead the new wave. Fast brand jumped to the top 3 of the hot list
158_模型_Power BI 使用 DAX + SVG 打通制作商业图表几乎所有可能
[deeply understand tcapulusdb technology] create a game area for document acceptance
[deeply understand tcapulusdb technology] create a game zone
. Net worker service adding a serial log record
Detailed explanation of route add command
【深入理解TcaplusDB技术】TcaplusDB新增机型
Training of long and difficult sentences in postgraduate entrance examination day90
158_ Model_ Power Bi uses DAX + SVG to open up almost all possibilities for making business charts
RMAN备份数据库_目录
Training of long and difficult sentences in postgraduate entrance examination day92
Analysis of global tea production, consumption and import and export trade: China's tea production ranks first in the world [figure]
将Graph Explorer搬上JupyterLab:使用GES4Jupyter连接GES并进行图探索
网络安全检测与防范 测试题(五)
Hash of redis command
《痞子衡嵌入式半月刊》 第 57 期
el-table高度自适应
158 Bar _ Modèle Power bi utilise Dax + SVG pour créer des diagrammes d'affaires presque toutes les possibilités
Command records of common data types for redis cli operations