目录
- Springboot解决前端请求跨域
- 原因
- 解决
- 总结
SpringboovFXrNEROpt解决前端请求跨域
Access to fetch at from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your n编程客栈eeds, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
原因
当前端请求的端口和后端接受请求的端口不一致
解决
创建一个配置文件CorConfig.Java,允许任何的请求头、请求方法访问。
此处是放开后端,允许前端访问,只需要设置访问源地址即可
package com.zhang.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsCophpnfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { // 当前跨域请求最大有效时长。这里默认1天 private static final long MAX_AGE = 24 * 60 * 60; http://www.devze.com @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguratiopythonn(); corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址(允许这个网站访问后台) corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 corsConfiguration.setMaxAge(MAX_AGE); source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 return new CorsFilter(source); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论