Spring @CrossOrigin不适用于DELETE方法 [英] Spring @CrossOrigin does not work with DELETE method

查看:415
本文介绍了Spring @CrossOrigin不适用于DELETE方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Spring @CrossOrigin annotation does not work with DELETE methods.

示例代码(在Groovy中):

Example code (in Groovy):

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

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

}

对于此代码,我得到了例外:

For this code I get the exception:


XMLHttpRequest无法加载 http:// localhost:8080 / rest / filename.txt 。所请求的
资源上没有
访问控制允许来源标头。因此,不允许
访问原始地址‘ http:// localhost:4200 。响应的HTTP状态代码为404。

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])
    没有帮助

  • 我省略了简洁的一些代码。实际的控制器还具有通过相同映射进行的GET请求,delete方法具有返回类型并产生JSON响应,以及我认为不会影响此问题的其他次要东西。

  • I tested it in Chrome 58 and Postman 4.10.7
  • According to https://spring.io/guides/gs/rest-service-cors/ by default @CrossOrigin allows only GET, HEAD and POST cross-origin requests. Although specifying @CrossOrigin(methods = [RequestMethod.GET, RequestMethod.DELETE]) did not help
  • I omitted some code for brevity. Actual controller also has GET request by the same mapping, delete method has return type and produces JSON response, and other minor stuff that I don't think affects the issue.

推荐答案

@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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆