java - 使用 Spring Boot 1.3.3-RELEASE 启用 CORS

标签 java spring spring-mvc spring-boot cors

我正在尝试使用 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 的示例?

--- 更新 ---

这是我的 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;
}

}

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

最佳答案

感谢您的回答和评论。

最后,答案必须是此处发布的答案的组合;我们被未发送内容类型的客户端消耗,因此当它尝试在 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);
        }
    };
}

但是,如果有人需要允许不带内容类型的请求选项,则需要使用 Simple CORS Filter 中提到的简单过滤器并更改以下行:

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

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

关于java - 使用 Spring Boot 1.3.3-RELEASE 启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35931529/

相关文章:

java - 如何根据模拟请求 JUnit4 测试 Spring 的 el-Expressions?

java - 如何在Spring初始化的一开始就初始化Spring bean?

机器人 RestClientException : no suitable HttpMessageConverter found

java - 查找特定的异常和相应的消息

java - 有没有办法在不通知文档它由 WebDriver 控制的情况下使用 Selenium WebDriver?

java - 如何为 Eclipse 项目中的文件指定正确的 URL

java - 在 hackerrank 中为相同的测试用例获取不同的输出

java - 不重复的字符串的排列

java - Spring MVC 如何决定 homecontroller 和 jsp 之间的冲突?

Java Spring View 格式化货币