如果前后端分离很可能出现跨域问题
允许跨域
/**
* controller基类,用于封装处理接口返回参数
*/
@CrossOrigin(origins = "*",allowCredentials = "true")//{"http://localhost:8081","http://127.0.0.1:8081"}
@Slf4j
public abstract class BaseAppController {}
或者
httpServletResponse.setContentType(CommonEnum.MediaTypes.JSON_UTF_8.getType());
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With, remember-me");
或者
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/app/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
设置自定义的响应头,可能出现设置了响应头但是前端取不到值的情况,注意下面的设置
response.addHeader("Access-Control-Expose-Headers", "响应头名称");//允许指定头信息,必须加这个否则前端去不到值
response.setHeader("响应头名称","响应头内容");