使用Spring Boot 1.3.3-RELEASE启用CORS [英] Enabling CORS using Spring Boot 1.3.3-RELEASE
问题描述
我想使用Spring Boot 1.3.3在示例项目中启用CORS。
我尝试按照 link ,但我仍然无法看到结果。
在我的Application.java中,我有以下代码。
@SpringBootApplication
public class Application {
private static final String [] REQUEST_METHOD_SUPPORTED = {GET,POST,PUT,PATCH,DELETE,OPTIONS ,HEAD};
public static void main(String [] args){
SpringApplication.run(Application.class,args);
}
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurerAdapter(){
@Override
public void addCorsMappings(CorsRegistry注册表){
registry.addMapping(/ api / rest / **)。allowedOrigins(*)。allowedHeaders(*)。allowedMethods(REQUEST_METHOD_SUPPORTED);
}
};
}
}
GET 和 POST
,但是当我尝试使用 PUT
> DELETE , OPTIONS
或 PATCH
。此外,我尝试添加此属性 spring.mvc.dispatch-options-request:true
,但仍然无法正常工作
我收到以下错误:
从handler [null]解析异常:org.springframework。 web.HttpRequestMethodNotSupportedException:不支持请求方法OPTIONS
调用@ExceptionHandler方法:public final org.springframework.http.ResponseEntity< java.lang.Object> org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)
不支持请求方法OPTIONS
Null ModelAndView返回给DispatcherServlet,名称为'dispatcherServlet':假设HandlerAdapter完成了请求处理
成功完成请求
你们有什么想法如何解决这个问题?你有一个教程,我可以看到使用CORS使用 PUT
或 PATCH
?
--- UPDATE ---
这是我的控制器
@RestController
@RequestMapping(value =/ api / rest / accounts,produce = MediaType.APPLICATION_JSON_VALUE)
public class AccountRestController {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountRestController.class);
@RequestMapping(method = RequestMethod.POST)
public帐户createAccount(@RequestBody帐户messageBody){
帐户帐户= buildAccount(messageBody);
return dbPersistAccount(account);
}
@RequestMapping(method = RequestMethod.DELETE,value =/ {id})
public void deleteAccount(@PathVariable(id)String id){
dbRemoveAccount(id);
}
@RequestMapping(method = RequestMethod.PUT,value =/ {id})
public void updateAccount(@PathVariable(id)String id,@ RequestBody帐户messageBody){
帐户帐户= dbGetAccount(id);
if(account == null){
throw new ResourceNotFoundException(Account not found with id = [+ id +]);
}
}
@RequestMapping(method = RequestMethod.PATCH,value =/ {id})
public void markAccount(@PathVariable(id )String id){
帐户account = dbGetAccount(id);
if(account == null){
throw new ResourceNotFoundException(Account not found with id = [+ id +]);
}
}
@RequestMapping(method = RequestMethod.GET,value =/ {id})
public Account getAccount(@PathVariable )String id){
帐户account = dbGetAccount(id);
if(account == null){
throw new ResourceNotFoundException(Account not found with id = [+ id +]);
}
return account;
}
}
我需要手动创建方法OPTIONS吗?我没有在我的控制器处理OPTIONS请求的方法
感谢您的答案和评论。
最后,答案必须是在这里张贴的答案的组合;我们得到一个没有发送内容类型的客户端消费,所以我们得到一个403,当它试图做一个OPTIONS之前PATCH或PUT;在其余客户端发送一个内容类型后,我们能够处理该请求。
因此,在我的情况下,以下代码工作,如果请求包括内容类型和你不需要做任何工作。
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurerAdapter(){
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping(/ api / rest / **)。allowedOrigins(*) .allowedHeaders(*)。allowedMethods(REQUEST_METHOD_SUPPORTED);
}
};但是,如果有人要求允许请求OPTIONS没有内容类型,那么,您需要使用此 Simple CORS Filter ,并更改以下行:
response.setHeader(Access-Control- Headers,);
我希望这可以帮助未来的某人。
I'm trying to enable CORS in a sample project using Spring Boot 1.3.3
I try to follow all the instructions from this link however I still not able to see results.
In my Application.java I have the following code.
@SpringBootApplication
public class Application {
private static final String[] REQUEST_METHOD_SUPPORTED = { "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD" };
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/rest/**").allowedOrigins("*").allowedHeaders("*").allowedMethods(REQUEST_METHOD_SUPPORTED);
}
};
}
}
Everything works when I use GET
and POST
, but when I try to use PUT
, DELETE
, OPTIONS
or PATCH
. Also, I try to add this property spring.mvc.dispatch-options-request:true
but still I don't get it work
I'm getting the following error:
Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'OPTIONS' not supported
Invoking @ExceptionHandler method: public final org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)
Request method 'OPTIONS' not supported
Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
Successfully completed request
Do you guys have an idea how can I solved this issue? Do you have a tutorial where I can see a sample working with CORS using PUT
or PATCH
?
--- UPDATE ---
Here is my controller
@RestController
@RequestMapping(value = "/api/rest/accounts", produces = MediaType.APPLICATION_JSON_VALUE)
public class AccountRestController {
private static final Logger LOGGER = LoggerFactory.getLogger(AccountRestController.class);
@RequestMapping(method = RequestMethod.POST)
public Account createAccount(@RequestBody Account messageBody) {
Account account = buildAccount(messageBody);
return dbPersistAccount(account);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void deleteAccount(@PathVariable("id") String id) {
dbRemoveAccount(id);
}
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
public void updateAccount(@PathVariable("id") String id, @RequestBody Account messageBody) {
Account account = dbGetAccount(id);
if (account == null) {
throw new ResourceNotFoundException("Account not found with id=[" + id + "]");
}
}
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
public void markAccount(@PathVariable("id") String id) {
Account account = dbGetAccount(id);
if (account == null) {
throw new ResourceNotFoundException("Account not found with id=[" + id + "]");
}
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public Account getAccount(@PathVariable("id") String id) {
Account account = dbGetAccount(id);
if (account == null) {
throw new ResourceNotFoundException("Account not found with id=[" + id + "]");
}
return account;
}
}
Do I need to create the method OPTIONS manually? I don't have in my controller a method that handles the OPTIONS request
解决方案 Thanks for your answers and comments.
At the end the answer has to be with a combination of the answers posted in here; we were getting consume by a client that did not send a content-type so we were getting a 403 when it try to do a OPTIONS before a PATCH or PUT; after the rest client sent a content-type we were able to handle the request.
So, in my case the following code works, if the request includes content-type and you don't need to do any work around.
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/rest/**").allowedOrigins("*").allowedHeaders("*").allowedMethods(REQUEST_METHOD_SUPPORTED);
}
};
}
However, if somebody has the requirement to allow requests OPTIONS without content-type, you need to use a simple filter which is mentioned in this Simple CORS Filter and change the following line:
response.setHeader("Access-Control-Allow-Headers", "");
I hope this can help somebody in the future.
这篇关于使用Spring Boot 1.3.3-RELEASE启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!