一般出現(xiàn)的問題:
has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’
問題原因:
跨域:指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對 javascript 施加的安全限制。
同源策略:是指協(xié)議,域名,端口都要相同,其中有一個不同都會產(chǎn)生跨域(重點:瀏覽器產(chǎn)生了跨域)
問題截圖:
以上兩張圖片就是瀏覽器報錯出現(xiàn)的跨域問題,但問題點又不一樣:第一張圖是未設(shè)置跨域,第二張圖是設(shè)置了多重跨域,所以無論前端還是后端都只能設(shè)置一層跨域
解決方案:
- 前端以vue為例(一般后端解決跨域問題比較方便,這樣當(dāng)項目部署到服務(wù)器上的時候也不會很麻煩),要在本地開發(fā)時,前端可以在項目中的vue.config.js中進行配置,相關(guān)示例如下:
devServer: {
// development server port 8000
port: 8000,
// If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
proxy: {
'/api': {
target: 'http://192.168.92.11',
ws: false,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
},
- 后端設(shè)置(重點:只能設(shè)置一層跨域)
(1)網(wǎng)關(guān)統(tǒng)一配置跨域
@Configuration
public class GulimallCorsConfiguration {
/**
* 功能描述:網(wǎng)關(guān)統(tǒng)一配置允許跨域
*
* @author cakin
* @date 2020/10/25
* @return CorsWebFilter 跨域配置過濾器
*/
@Bean
public CorsWebFilter corsWebFilter(){
// 跨域配置源
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 跨域配置
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1 配置跨域
// 允許所有頭進行跨域
corsConfiguration.addAllowedHeader("*");
// 允許所有請求方式進行跨域
corsConfiguration.addAllowedMethod("*");
// 允許所有請求來源進行跨域
corsConfiguration.addAllowedOrigin("*");
// 允許攜帶cookie進行跨域
corsConfiguration.setAllowCredentials(true);
// 2 任意路徑都允許第1步配置的跨域
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
(2)服務(wù)內(nèi)設(shè)置跨域:注解@CrossOrigin
文章來源:http://www.zghlxwxcb.cn/news/detail-587177.html
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
對于跨域還有其他解決方案,重要的是要知道出現(xiàn)問題的原因以及搜索問題的思路文章來源地址http://www.zghlxwxcb.cn/news/detail-587177.html
到了這里,關(guān)于跨域問題記錄:has been blocked by CORS policy_ The ‘Access-Control-Allow-Origin‘的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!