2021-02-20 分類: 網站建設
1、什么是跨越?
2、為什么會產生跨域請求?
3、什么是同源策略?
4、為什么瀏覽器要使用同源策略?
發請求,這時瀏覽器就會報錯,這就是跨域報錯。
解決方案有五:
1、前端使用jsonp (不推薦使用)
$.ajax({
url: 'http://192.168.1.114/yii/demos/test.php', //不同的域
type: 'GET', // jsonp模式只有GET 是合法的
data: {
'action': 'aaron'
},
dataType: 'jsonp', // 數據類型
jsonp: 'backfunc', // 指定回調函數名,與服務器端接收的一致,并回傳回來
})
2、后臺Http請求轉發
try {
HttpClient client = HttpClients.createDefault(); //client對象
HttpGet get = new HttpGet("http://localhost:8080/test"); //創建get請求
CloseableHttpResponse response = httpClient.execute(get); //執行get請求
String mes = EntityUtils.toString(response.getEntity()); //將返回體的信息轉換為字符串
System.out.println(mes);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
3、后臺配置同源Cors (推薦)
在SpringBoot2.0 上的跨域 用以下代碼配置 即可好解決你的前后端跨域請求問題
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 實現基本的跨域請求
* @author linhongcun
*
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/*是否允許請求帶有驗證信息*/
corsConfiguration.setAllowCredentials(true);
/*允許訪問的客戶端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允許服務端訪問的客戶端請求頭*/
corsConfiguration.addAllowedHeader("*");
/*允許訪問的方法名,GET POST等*/
corsConfiguration.addAllowEDMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
4、使用SpringCloud網關
5、使用nginx做轉發
server {
listen 80;
server_name www.my.com;
location /A {
proxy_pass http://a.a.com:81/A;
index index.html index.htm;
}
location /B {
proxy_pass http://b.b.com:81/B;
index index.html index.htm;
}
}
server {
listen 80;
server_name b.b.com;
location /Api {
proxy_pass http://b.b.com:81/Api;
index index.html index.htm;
}
}
歡迎工作一到五年的Java工程師朋友們加入Java程序員開發: 721575865
群內提供免費的Java架構學習資料(里面有高可用、高并發、高性能及分布式、Jvm性能調優、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!
名稱欄目:解決網站跨域的幾種方式
文章URL:http://www.js-pz168.com/news1/102001.html
成都網站建設公司_創新互聯,為您提供網站設計、虛擬主機、關鍵詞優化、軟件開發、域名注冊、App設計
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯
猜你還喜歡下面的內容