前后端分离的开发模式下,通常在开发过程中,前后端项目占用不同的端口,这样就会出现前端访问后端数据过程跨域的问题
可通过下面两种方式解决eladmin前端跨域问题:
1. 后端修改
以java SpringBoot工程为例,添加WebMvcConfigurer
配置:
package com.example.mgr.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*/*")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
};
}
}
注意注册器中添加的映射模式为"/*/*"
,这代表会对前端访问的http://localhost:port/xxx/yyy模式的地址做跨域允许。
2. 修改前端代理

这样修改之后需保证在使用
axios
进行接口调用的时候使用 /api/xxx
的模式。举例:
Axios.post('/api/auth/login', param,{headers:headers});
考虑到开发的便捷性,我使用的是第一方法
网友评论