后端运行了一个Spring Boot应用程序。我已经实现了几个GET / POST / PUT / DELETE API。
前端(AngularJS)可以执行GET和POST,但在请求PUT和DELETE时会获得403 ERROR。 我已经添加了允许的起源(如果没有它,POST将无法工作)来解决CORS问题。
CORS设置:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("https://xxx1.com", "https://xxx2.com");
}
};
}
CSRF设置:
http.csrf().disable();
暂时停用
以下是我对DELETE的实现:
@DeleteMapping("/listings/{id}")
public ResponseEntity<Void> deleteListings(@PathVariable Long id) {
log.debug("REST request to delete listings : {}", id);
this.listingsService.delete(id);
return ResponseEntity.status(HttpStatus.OK).body(null);
}
有人可以帮忙吗?真的很感激!
答案 0 :(得分:2)
您似乎可以链接到allowedMethods("GET","POST","PUT","DELETE")
according to the docs。
这有帮助吗?
答案 1 :(得分:2)
在spring-boot
项目中创建CORSFilter.java文件。
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
/**
* CORS filter for http-request and response
*/
public CORSFilter() {
}
/**
* Do Filter on every http-request.
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
/**
* Destroy method
*/
@Override
public void destroy() {
}
/**
* Initialize CORS filter
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}