欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 解决跨域问题

解决跨域问题

2025/5/2 18:06:30 来源:https://blog.csdn.net/sunyanchun/article/details/143824747  浏览:    关键词:解决跨域问题
什么是跨域?

跨域指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。跨域只出现在前端,后端不会出现。

怎么解决跨域?
1、使用nginx转发

同源策略只限制于浏览器端的服务器,当后端服务器访问后端服务器时即使是非同源也是可以正常访问。

前端jQuery发送ajax请求

$.ajax({url: 'http://localhost:8081/cors/1',type: 'GET',success: function (result) {console.log(result);}
})

nginx配置 

    server {listen       8081;server_name  localhost;location / {root   html;index  index.html index.htm;}location /cors/ {proxy_pass http://localhost:8080/user/;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}
2、后端使用@CrossOrigin注解
@GetMapping("{id}")
@CrossOrigin("http://localhost:8081") // 跨域来源
public Result getUser1(@PathVariable Long id){User user = new User();return new Result<>(200, "success", user);
}
3、配置一个实现WebMvcConfigurer的配置类
@Configuration
public class CorsWebMvcConfigurer implements WebMvcConfigurer {/*** 全局Cors配置* @param registry*/@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/user/*") // 映射服务器中哪些接口允许跨域访问.allowedOrigins("http://localhost:8080") // 配置哪些来源有权限跨域访问.allowedMethods("GET", "POST", "DELETE", "PUT"); // 配置允许跨域访问的方法}
}
4、配置一个CorsFilter的Bean
@Configuration
public class MyCorsFilter {@Beanpublic CorsFilter corsFilter() {// 1.创建Cors配置对象CorsConfiguration config = new CorsConfiguration();// 支持域config.addAllowedOriginPattern("*");// 是否发送Cookieconfig.setAllowCredentials(true);// 支持请求方式config.addAllowedMethod("*");// 2.添加地址映射UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**", config);// 3.返回CorsFilter对象return new CorsFilter(corsConfigurationSource);}
}
5、JSONP

只支持get请求,它会默认在请求中加上一个?callback=xxx的参数,它的值是随机的,这个值会作为秘钥的形式传给后端,你可以在ajax中通过jsonp:'a'、jsonpCallback:'cc'来设置它的名字和值

前端jQuery发送ajax请求

$.ajax({url: 'http://localhost:8081/cors/jsonp/1',dataType: 'jsonp',type: 'GET',success: function (result) {console.log(result);}
})

后端代码

@GetMapping("/jsonp/{id}")
public JSONPObject getUser(@PathVariable Long id, String callback) {User user = new User();return new JSONPObject(callback, new Result<>(200, "SUCCESS",user));
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词