1. 程式人生 > 其它 >No ‘Access-Control-Allow-Origin‘ header is present on the requested resource 跨域錯誤

No ‘Access-Control-Allow-Origin‘ header is present on the requested resource 跨域錯誤

技術標籤:跨域問題

No ‘Access-Control-Allow-Origin’ header is present on the requested resource 錯誤
在這裡插入圖片描述
翻譯是找不到資源路徑在這裡插入圖片描述
1 前端解決跨域(不建議):
將crossDomain設定為true

$.ajax({
    url: 'http://www.domain2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 請求方式為jsonp
     crossDomain: true,
	 success: function(data) {},
    data:
{} });

2.後端跨域:

在Controller上面新增@CrossOrigin註解方式在這裡插入圖片描述

注意 :如果使用了@CrossOrigin註解 和 其他方式的跨域同時存在 會多次進行跨域 會出現錯誤 使用選擇其一就行

用攔截器實現

public class CustomInterceptor implements HandlerInterceptor{

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
//解決跨域問題 response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Methods","*"); response.setHeader("Access-Control-Allow-Headers","*"); return true; } }

用Gateway實現

@Configuration
public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }