gpt4 book ai didi

Spring @CrossOrigin 不适用于 DELETE 方法

转载 作者:行者123 更新时间:2023-12-04 01:16:06 24 4
gpt4 key购买 nike

Spring @CrossOrigin 注释不适用于 DELETE 方法。

示例代码(在 Groovy 中):

@CrossOrigin
@RestController
@RequestMapping('/rest')
class SpringController {

@RequestMapping(value = '/{fileName}', RequestMethod.DELETE)
void deleteFile(@PathVariable fileName) {
// logic
}

}

对于这段代码,我得到了异常:

XMLHttpRequest cannot load http://localhost:8080/rest/filename.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.



笔记:
  • 我在 Chrome 58 和 Postman 4.10.7
  • 中测试了它
  • 根据 https://spring.io/guides/gs/rest-service-cors/经过
    默认@CrossOrigin 只允许 GET、HEAD 和 POST 跨域
    要求。虽然指定 @CrossOrigin(methods =
    [RequestMethod.GET, RequestMethod.DELETE])
    没有帮助
  • 为简洁起见,我省略了一些代码。实际 Controller 也有相同映射的 GET 请求,delete 方法有返回类型并产生 JSON 响应,以及我认为不会影响问题的其他小东西。
  • 最佳答案

    @Configuration
    public class AppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("your cross origin url")
    .allowedOrigins("your cross origin host/url")
    .allowedHeaders("Access-Control-Allow-Origin", "*")
    .allowedHeaders("Access-Control-Allow-Headers", "Content-Type,x-requested-with").maxAge(20000)
    .allowCredentials(false)
    .allowedMethods("DELETE");
    }
    }

    // in your controller
    @RequestMapping(value = '/{fileName:.+}', RequestMethod.DELETE)
    void deleteFile(@PathVariable fileName) {
    // your custom logic
    }

    关于Spring @CrossOrigin 不适用于 DELETE 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44067871/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com