報錯: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:80' is therefore not allowed access
百度了兩三個小時,很多都說設置config/index.js 的“proxyTable”屬性,我設置了並沒有用,也可能是我沒寫對
調用地址直接寫代理地址會自動拼接當前vue服務的域名,最後當然是報404。。。
proxyTable: {
'/api':{
target: 'http://localhost:80/',//設置你調用的接口域名和端口號 別忘了加http
changeOrigin: true,//如果需要跨域
pathRewrite: {
'^/api': 'http://localhost:80/',//調用接口直接寫‘/api/user/add’即可
}
}
},
跨域一直是個很玄學的問題,前端沒辦法了我就想在後端解決,
只需要加一個配置類, 重寫addCorsMappings方法即可
package com.xxx.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.Executors;
/**
* @description {跨域請求支持}
* <p>
* Create by xxxxx on 2020/3/31 14:11.
*/
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
@Override
public void addCorsMappings(CorsRegistry registry) {
/*
* 請求常用的三種配置,*代表允許所有,當時你也可以自定義屬性(比如header只能帶什麼,只能是post方式等等)
*/
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*");
}
@Override
protected void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
configurer.setDefaultTimeout(30000);
}
}
雖然這個可以解決跨域問題,讓axios讀取到後端數據,
但是使用此方法配置之後再使用自定義攔截器時跨域相關配置就會失效。
原因是請求經過的先後順序問題,當請求到來時會先進入攔截器中,而不是進入Mapping映射中,所以返回的頭信息中並沒有配置的跨域信息。瀏覽器就會報跨域異常。
正確的解決跨域問題的方法時使用CorsFilter過濾器。代碼如下:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", addCorsConfig());
return new CorsFilter(source);
}
private CorsConfiguration addCorsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}