问题描述:
在写好后端程序和前端进行交互的时候,发现在前端虽然状态响应码是200,但是返回不了任何数据。使用postman测试没有任何问题
问题分析:
问题的根源在于跨域上,前端是vue项目,使用axios与后端交互。之前此类项目的前后端都部署在同一台电脑上时没有出现过问题,但是前后端分离部署就不能正常使用了。查了很多资料后目前暂时可以解决了,后面可能还会出现同样的问题,暂时先将解决方法记录下来
在后端项目中创建一个新的配置类,代码如下
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;
/**
* ClassName: CustomCorsConfig
* Package: test.config
*
* @author qqq
* @date 2024/5/21
*/
@Configuration
public class CustomCorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 允许的来源域名,* 表示允许所有域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
// .allowedHeaders("Content-Type", "X-Requested-With") // 允许的请求头
.maxAge(3600); // 允许的缓存时间,单位为秒
}
};
}
}
这样竟然神奇地成功了?!!不明白原理是什么,但是能用好用就行,之后出现问题会再解决