Spring Boot Data Rest + CORS not being enabled properly for OPTIONS/DELETE

后端 未结 4 1040
暖寄归人
暖寄归人 2020-12-21 07:08

I\'ve got an extremely simple example that I can\'t get to work.

I have my domain that models my database, and my Repository.

public interface MyTes         


        
4条回答
  •  悲哀的现实
    2020-12-21 07:37

    I seem to have the same issue. CrossOrigin config works fine with GET/PUT/POST, but when I request OPTIONS for my Spring PostMapping method the response omits the Access-Control-Allow-Methods header:

    @CrossOrigin
    public class ArticleController {
    
    @DeleteMapping("/{uuid}")
    public void delete(@PathVariable String uuid) throws ArticleNotFoundException {
        articleService.delete(uuid);
    }
    

    If I curl for DELETE, I get a HTTP 200 including Access-Control-Allow-Methods:

    $ curl -v -H "Access-Control-Request-Method: DELETE" -H "Origin: http://localhost:4200" -X OPTIONS http://localhost:8080/article/someuuid
    < HTTP/1.1 200
    < Access-Control-Allow-Origin: http://localhost:4200
    < Access-Control-Allow-Methods: PUT,POST,GET,DELETE,OPTIONS
    < Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
    

    If I curl for OPTIONS, I get a 403:

    $ curl -v -H "Access-Control-Request-Method: OPTIONS" -H "Origin: http://localhost:4200" -X OPTIONS http://localhost:8080/article/someuuid
    < HTTP/1.1 403
    

    Am I missing something here?

    EDIT 1:

    If I add this mapping to the controller (based on Enable CORS for OPTIONS request using Spring Framework ):

    @RequestMapping(
            value = "/**",
            method = RequestMethod.OPTIONS
    )
    public ResponseEntity handle() {
        return new ResponseEntity(HttpStatus.OK);
    }
    

    This results in:

    $ curl -v -H "Access-Control-Request-Method: OPTIONS" -H "Origin: http://localhost:4200" -X OPTIONS http://localhost:8080/article/someuuid
    < HTTP/1.1 200
    < Access-Control-Allow-Origin: *
    < Access-Control-Allow-Methods: OPTIONS
    < Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
    

    But it doesn't solve the issue for Angular which still gives a 403

    EDIT 2: I've been able to fix this with the following Controller-code:

    @RequestMapping("/article")
    @CrossOrigin(origins="http://localhost:4200",
        methods = {RequestMethod.PUT, RequestMethod.POST, RequestMethod.GET, RequestMethod.DELETE, RequestMethod.OPTIONS}
        )
    public class ArticleController {
    
    @RequestMapping(
            value = "/{uuid}",
            method = { RequestMethod.DELETE })
    public void delete(@PathVariable String uuid) throws ArticleNotFoundException {
        articleService.delete(uuid);
    }
    
    @RequestMapping(method = { RequestMethod.OPTIONS})
    public ResponseEntity handle() {
        return new ResponseEntity(HttpStatus.OK);
    }
    

提交回复
热议问题