我是靠谱客的博主 糟糕毛豆,这篇文章主要介绍跨域Access to XMLHttpRequest at ‘http://localhost:8181/list‘ from origin ‘http://localhost:8080‘ has什么是跨域SpringBoot项目中解决跨域的3种方案Vue解决跨域的方案,现在分享给大家,希望可以做个参考。

什么是跨域

跨域是指浏览器不能执行其他网站的脚本。它是浏览器同源策略造成的,是浏览器对JS实施的安全限制
例如:
Vue:http://localhost:8080
SpringBoot:http://localhost:8181/list
在前后端分离中,Vue调用SpringBoot方法时,产生如下错误:

复制代码
1
2
3
4
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.

后端已经接收到请求,并返回了,但前端没有收到

同源策略

同源:协议、域名、端口3个都相同

SpringBoot项目中解决跨域的3种方案

1、在目标方法上添加@CrossOrigin注解

复制代码
1
2
3
4
5
6
@GetMapping("/list") @CrossOrigin public List<String> list(){ .... }

2、添加CORS过滤器
CORS:Cross Origin Resource Sharing跨域资源共享

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Configuration public class CorsConfig{ /** * 跨域配置 */ @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 设置访问源地址 config.addAllowedOriginPattern("*"); // 设置访问源请求头 config.addAllowedHeader("*"); // 设置访问源请求方法 config.addAllowedMethod("*"); // 有效期 1800秒 // config.setMaxAge(1800L); // 添加映射路径,拦截一切请求 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); // 返回新的CorsFilter return new CorsFilter(source); } }

3、实现WebMvcConfigure接口,重写addCorsMappings方法

复制代码
1
2
3
4
5
6
7
8
9
10
@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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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变为空字符 } } }, disableHostCheck: true // https: true, }, }

.env.development

复制代码
1
2
3
4
5
6
7
8
9
10
# 开发环境配置 ENV = 'development' # 基础api(根据实际情况,自行配置,下为示例) 协议://域名:后端项目的端口号(对应服务器的接口地址)开发环境(本地)/ 测试环境或开发环境(代理地址/测试、开发地址) # localhost也能写成本地的端口,通过cmd,ipconfig查 VUE_APP_BASE_API = 'http://localhost:8090' # 路由基础路径 VUE_APP_BASE_URL = '/'

最后

以上就是糟糕毛豆最近收集整理的关于跨域Access to XMLHttpRequest at ‘http://localhost:8181/list‘ from origin ‘http://localhost:8080‘ has什么是跨域SpringBoot项目中解决跨域的3种方案Vue解决跨域的方案的全部内容,更多相关跨域Access内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部