【发布时间】:2021-01-09 14:13:48
【问题描述】:
我正在尝试在 Spring + Angular 项目中实现对静态资源的处理请求。当 Spring 应用在 http://localhost:8080 上运行时,Angular 应用在 http://localhost:4200 上运行。
因此,当我需要获取图像时,Angular 会发送一个类似于 http://localhost:4200/screenShots/image-name.jpg 的请求。为了处理这类请求,我创建了WebConfig 类:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String path = "file:///" + *path to folder with images on my PC*
registry.addResourceHandler("/screenShots/**")
.addResourceLocations(path);
}
}
它不起作用,我得到 404 (Not Found) 错误。我已经尝试过 addind 和删除 @EnableWebMvc 和 @CrossOrigin 注释,尝试在我的类中添加 addCorsMappings() 方法,但没有任何帮助。
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/screenShots/**")
.allowedOrigins("http://localhost:4200");
}
但是,当我将 http://localhost:8080/screenShots/image-name.jpg (changed :4200 to :8080) 字符串放在 Google 地址栏中时,它会按预期返回我的图像,所以我想知道有没有办法添加某种@CrossOrigin 注释替代资源处理程序因为我还没有在 Internet 上找到任何解决方案。谢谢!
Github repo 适合那些好奇的人(只有 gameImagesRelease 分支包含当前代码):https://github.com/Vladyslav-Bahlai/OktenGames/tree/gameImagesRelease
【问题讨论】:
标签: java spring spring-boot spring-mvc