解决跨域问题

什么是跨域?

跨域指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对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
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/user/*") // 映射服务器中哪些接口允许跨域访问
				.allowedOrigins("http://localhost:8080") // 配置哪些来源有权限跨域访问
				.allowedMethods("GET", "POST", "DELETE", "PUT"); // 配置允许跨域访问的方法
    }
}
4、配置一个CorsFilter的Bean
@Configuration
public class MyCorsFilter {
	@Bean
	public CorsFilter corsFilter() {
		// 1.创建Cors配置对象
		CorsConfiguration config = new CorsConfiguration();
		// 支持域
		config.addAllowedOriginPattern("*");
		// 是否发送Cookie
		config.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));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunyanchun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值