当前位置:网站首页>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 !
边栏推荐
- 解决sublime Text3 package control 无法安装插件问题
- 158_ Model_ Power Bi uses DAX + SVG to open up almost all possibilities for making business charts
- Training of long and difficult sentences in postgraduate entrance examination day87
- 两轮市场红海,利尔达芯智行如何乘风破浪?
- GNU nano
- Some recursive and iterative problem solving ideas of binary tree (clear and easy to understand)
- [deeply understand tcapulusdb technology] tmonitor background one click installation
- Training of long and difficult sentences in postgraduate entrance examination day90
- JVM problem replication
- Command records of common data types for redis cli operations
猜你喜欢

利尔达蓝牙空调接收器方案助力打造更舒适的公路生活
![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]
![[compréhension approfondie de la technologie tcaplusdb] sauvegarde des données d'affaires tcaplusdb](/img/7f/6d42dc96348001dd6ebd724a44a123.png)
[compréhension approfondie de la technologie tcaplusdb] sauvegarde des données d'affaires tcaplusdb

【深入理解TcaplusDB技术】 Tmonitor模块架构

Redis6

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

07 local method stack
![[elt.zip] openharmony paper Club - witness file compression system erofs](/img/db/2f1c85ebd4ce9b84d9fd5406a8de4b.png)
[elt.zip] openharmony paper Club - witness file compression system erofs

How to sort massive data? How to process data between memory and hard disk?
![[in depth understanding of tcapulusdb technology] new models of tcapulusdb](/img/10/f94a5e1ebeaa803c754dd77351950f.png)
[in depth understanding of tcapulusdb technology] new models of tcapulusdb
随机推荐
RMAN backup database_ Restart RMAN backup
LeetCode 3. Longest substring without repeated characters & sliding window
C ASP, net core framework value transfer method and session use
Redis command string
GNU nano
快手616战报首发,次抛精华引新浪潮,快品牌跃入热榜top3
【深入理解TcaplusDB技术】如何实现Tmonitor单机安装
[compréhension approfondie de la technologie tcaplusdb] sauvegarde des données d'affaires tcaplusdb
RMAN备份数据库_跳过脱机,只读和不可访问的文件
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
One article solves all search backtracking problems of Jianzhi offer
Training of long and difficult sentences in postgraduate entrance examination day91
RMAN backup database_ Use RMAN for split mirror backup
GNU nano
solidity 合约地址转钱包、钱包地址转合约
Training of long and difficult sentences in postgraduate entrance examination day86
Analysis of China's medical device industry development environment (PEST) in 2021: the awareness of medical care is enhanced, and the demand for medical device products is also rising [figure]
03 runtime data area overview and threads
Meaning of% in C language
Trample hole record -- a series of coincidences caused by thread pool rejection policy