1
我創建使用Sppring啓動一個REST上傳服務:SpringBoot不啓用@CroOrigin。 Angular2 +的WebPack客戶
@CrossOrigin
@RestController
@RequestMapping("/upload")
public class FileUploadHandler {
@PostMapping("/doUpload")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File(file.getName() + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + file.getName() + " into " + file.getName() + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + file.getName() + " => " + e.getMessage();
}
} else {
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "Some error... ";
}
}
}
我使用的是Angular2 +的WebPack客戶端使用該服務。問題是,當我嘗試訪問服務時,我收到了一個CROS塊。
XMLHttpRequest cannot load http://localhost:8080/kti-cms-spring/upload/doUpload. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ac1068:8080' is therefore not allowed access.
我使用glassfish4作爲應用程序服務器。
我的配置:
@Configuration
@ComponentScan("de.awinta.kti.cms")
public class MainConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// likely you should limit this to specific origins
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(Boolean.TRUE);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
應用程序入口點
@SpringBootApplication
public class KtiCmsApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(KtiCmsApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<KtiCmsApplication> applicationClass = KtiCmsApplication.class;
}
我的想法如何得到這個工作,並想嘗試老式JAX-RS服務曝光。也許這裏有人有一個關於如何讓這個春天工作的想法。
嘿。感謝您的反饋。在添加配置類後,它仍然在說相同的錯誤。我相信但是,你認爲Glassfish可能無法正確加載應用程序嗎? – user2960896
對不起,我對Glassfish不太瞭解,從你的例子中無法看出來。可以肯定的是,您必須在Spring引導中啓用自動配置(通過EnableAutoConfiguration或@SpringBootApplication註釋) – Pascal
添加註釋並沒有幫助:(我添加了應用程序配置和入口點以解決問題,也許它有幫助。 – user2960896