【问题标题】:Wrong CORS configuration in a SpringBoot projectSpringBoot项目中的CORS配置错误
【发布时间】:2021-01-21 04:41:30
【问题描述】:

我正在开发一个 CRUD 应用程序,它将在 SpringBoot 部分中提供 REST(它也将有一个 Angular 部分,使用 JSON)。 SpringBoot 部分提供优雅的 JSON(针对 MySQL 数据库的查询),但是当我运行尝试删除记录的部分时,我收到 405 错误:

“出现意外错误(类型=不允许的方法,状态=405)。”

这是失败的代码(它正在调用@Service)

@RequestMapping(value = "/avisos/delete/{id}", method = RequestMethod.DELETE) 
public ResponseEntity<Void> borraAviso(@RequestParam("id") Long id) {
   
    boolean isRemoved;
    isRemoved = avisoService.borraAviso(id);

    if (!isRemoved) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    else
        return new ResponseEntity<>(HttpStatus.OK);
        
}

这是 CORS 配置文件:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                //.allowedMethods("GET", "POST");
                .allowedMethods("");
    }
}

该程序在 Linux Mint 盒子中运行,但我也在 W8 盒子中进行了测试,我得到了同样的错误。 (我使用的是 Spring Tool Suite 4,版本:4.8.0.RELEASE 和 Maven)。

【问题讨论】:

    标签: spring-boot cors


    【解决方案1】:

    方法的声明有一个问题

    @RequestMapping(value = "/avisos/delete/{id}", 方法 = RequestMethod.DELETE) 公共响应实体 borraAviso(@RequestParam("id") 长 id) {

    这里的idPathVariable。所以正确的声明应该是

    @RequestMapping(value = "/avisos/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> borraAviso(@PathVariable("id") Long id) {
    

    默认情况下,GETHEADPOST 方法在未覆盖的情况下允许用于 CORS。

    如果你想允许DELETE 方法,那么下面的配置应该可以工作。

    registry.addMapping("/**")
        .allowedOrigins("http://localhost:4200")
        .allowedMethods(HttpMethod.GET.name(),
             HttpMethod.HEAD.name(),
             HttpMethod.POST.name(),
             HttpMethod.DELETE.name()
        );
    

    【讨论】:

    • 嗨,GSSwain:之后我得到相同的“.... .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法'GET']”
    • 你可以创建一个示例项目并在这里分享 github url 吗?
    猜你喜欢
    • 2017-08-16
    • 2017-06-01
    • 2014-09-12
    • 2021-05-14
    • 2020-10-11
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多