在用CorsRegistry / @ CrossOrigin配置Spring之后仍然出现CORS错误

时间:2018-11-28 02:15:56

标签: spring rest http spring-boot cors

使用CorsRegistry配置/ @CrossOrigin和im发送XMLHttpRequest时仍然收到CORS错误的已配置Spring后端。

请注意,这仅在我发送DELETE请求时才发生。对于GET和POST来说似乎工作正常。

@RestController
@RequestMapping(path="abouts",
                produces="application/json",
                consumes="application/json")
@CrossOrigin(origins="*")
public class AboutController {

    private AboutRepository aboutRepo;

    public AboutController(AboutRepository aboutRepo) {
        this.aboutRepo = aboutRepo;
    }

    @GetMapping
    public Iterable<About> getAbouts() {
        return aboutRepo.findAll();
    }

    @GetMapping("/{aboutId}")
    public ResponseEntity<About> aboutById(@PathVariable("aboutId") Long id) {
        Optional<About> optAbout = aboutRepo.findById(id);
        if (optAbout.isPresent()){
            return new ResponseEntity<>(optAbout.get(), HttpStatus.OK);
        }
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public About postAbout(@RequestBody About about) {
        return aboutRepo.save(about);
    }

    @PutMapping("/{aboutId}")
    public About putAbout(@RequestBody About about) {
        return aboutRepo.save(about);
    }

    @DeleteMapping("/{aboutId")
    @ResponseStatus(code = HttpStatus.NO_CONTENT)
    public void deleteEvent (@PathVariable("aboutId") Long aboutId) {
        try {
            aboutRepo.deleteById(aboutId);
        }catch (EmptyResultDataAccessException e) {
        }
    }
}

JS

function deleteAbout (e) {
    let id = e.target.getAttribute("id").slice(5);
    let xhr = new XMLHttpRequest();
    xhr.onload = () => {
        getAbouts();
    }
    xhr.open("DELETE","http://localhost:8080/abouts/" + id);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
    xhr.send();
}

window.addEventListener("load", getAbouts);

1 个答案:

答案 0 :(得分:0)

语法错误..缺失}的删除方法,弹簧控制器...对不起,伙计们

我修复它后就可以工作