什么是跨域
跨域是指瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是瀏覽器同源策略造成的,是瀏覽器對JS實(shí)施的安全限制
例如:
Vue:http://localhost:8080
SpringBoot:http://localhost:8181/list
在前后端分離中,Vue調(diào)用SpringBoot方法時,產(chǎn)生如下錯誤:
Access to XMLHttpRequest at 'http://localhost:8181/list' from origin
'http://localhost:8080' has been blocked by CORS policy:No
'Access-Control-Allow-Origin' header is present on the requested resource.
后端已經(jīng)接收到請求,并返回了,但前端沒有收到
同源策略
同源:協(xié)議、域名、端口3個都相同
SpringBoot項(xiàng)目中解決跨域的3種方案
1、在目標(biāo)方法上添加@CrossOrigin注解
@GetMapping("/list")
@CrossOrigin
public List<String> list(){
....
}
2、添加CORS過濾器
CORS:Cross Origin Resource Sharing跨域資源共享
@Configuration
public class CorsConfig{
/**
* 跨域配置
*/
@Bean
public CorsFilter corsFilter()
{
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 設(shè)置訪問源地址
config.addAllowedOriginPattern("*");
// 設(shè)置訪問源請求頭
config.addAllowedHeader("*");
// 設(shè)置訪問源請求方法
config.addAllowedMethod("*");
// 有效期 1800秒
// config.setMaxAge(1800L);
// 添加映射路徑,攔截一切請求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
}
}
3、實(shí)現(xiàn)WebMvcConfigure接口,重寫addCorsMappings方法
@Configuration
public class CorsConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS").allowCredentials(true).maxAge(3600)
.allowedHeaders("*");
}
}
Vue解決跨域的方案
1、vue.config.js文章來源:http://www.zghlxwxcb.cn/news/detail-400617.html
module.exports = {
devServer: {
host: '0.0.0.0',
port: '80',
// 自動打開瀏覽器
open: true,
proxy: {
// detail: https://cli.vuejs.org/config/#devserver-proxy
['/api']: { // /api 表示攔截以/api開頭的請求路徑
target: process.env.VUE_APP_BASE_API, // 跨域的域名(不需要寫路徑) 路徑在.env.development
changeOrigin: true, // 重寫路徑
pathRewrite: {
['^/api']: '' // 把/api變?yōu)榭兆址? }
}
},
disableHostCheck: true
// https: true,
},
}
.env.development文章來源地址http://www.zghlxwxcb.cn/news/detail-400617.html
# 開發(fā)環(huán)境配置
ENV = 'development'
# 基礎(chǔ)api(根據(jù)實(shí)際情況,自行配置,下為示例) 協(xié)議://域名:后端項(xiàng)目的端口號(對應(yīng)服務(wù)器的接口地址)開發(fā)環(huán)境(本地)/ 測試環(huán)境或開發(fā)環(huán)境(代理地址/測試、開發(fā)地址)
# localhost也能寫成本地的端口,通過cmd,ipconfig查
VUE_APP_BASE_API = 'http://localhost:8090'
# 路由基礎(chǔ)路徑
VUE_APP_BASE_URL = '/'
到了這里,關(guān)于跨域Access to XMLHttpRequest at ‘http://localhost:8181/list‘ from origin ‘http://localhost:8080‘ has的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!