【问题标题】:Enabling CORS using Spring Boot 1.3.3-RELEASE使用 Spring Boot 1.3.3-RELEASE 启用 CORS
【发布时间】:2016-06-26 04:26:46
【问题描述】:

我正在尝试使用 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) {
                registry.addMapping("/api/rest/**").allowedOrigins("*").allowedHeaders("*").allowedMethods(REQUEST_METHOD_SUPPORTED);
            }
        };
    }
}

当我使用GETPOST 时一切正常,但当我尝试使用PUTDELETEOPTIONSPATCH 时。另外,我尝试添加此属性spring.mvc.dispatch-options-request:true,但仍然无法正常工作

我收到以下错误:

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

成功完成请求

你们知道我该如何解决这个问题吗?您是否有教程,我可以在其中看到使用 PUTPATCH 使用 CORS 的示例?

--- 更新 ---

这是我的控制器

@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;
}

}

我需要手动创建方法 OPTIONS 吗?我的控制器中没有处理 OPTIONS 请求的方法

【问题讨论】:

  • 这些方法映射到你的控制器中了吗?
  • @CrossOrigin(origins = "*") @RequestMapping(method = RequestMethod.DELETE) public void del(){ }...
  • 如果您发送明确的OPTIONS 请求,那么控制器必须支持它们。

标签: java spring spring-mvc spring-boot cors


【解决方案1】:

感谢您的回答和 cmets。

最后,答案必须是此处发布的答案的组合;我们被一个没有发送内容类型的客户端消费,所以当它尝试在 PATCH 或 PUT 之前执行 OPTIONS 时,我们得到了 403;在其余客户端发送内容类型后,我们能够处理请求。

因此,在我的情况下,如果请求包含内容类型并且您不需要做任何工作,则以下代码有效。

 @Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/rest/**").allowedOrigins("*").allowedHeaders("*").allowedMethods(REQUEST_METHOD_SUPPORTED);
        }
    };
}

但是,如果有人要求允许没有 content-type 的请求 OPTIONS,您需要使用Simple CORS Filter 中提到的简单过滤器并更改以下行:

response.setHeader("Access-Control-Allow-Headers", "");

我希望这可以帮助将来的人。

【讨论】:

  • 感谢@Rogelio 编译答案。这种方法效果很好。从 SpringBoot 1.3.0 开始,您只需要添加 @CrossOrigin 注释和其他可选配置属性即可。它的作用就像魅力
猜你喜欢
  • 2016-08-31
  • 2017-07-29
  • 2020-05-29
  • 2017-08-10
  • 2021-04-03
  • 2020-07-11
  • 2020-01-09
  • 2019-01-14
相关资源
最近更新 更多