【发布时间】:2020-01-24 17:22:51
【问题描述】:
关于在春季启用CORS 有很多问题,但似乎并非所有这些问题都有有效答案,或者接受的答案对我的情况不起作用。所以我正在创建这个问题,看看是否有人可以帮助我。
我一直在尝试启用 CORS 对我的 API 响应的响应,我尝试将 @CrossOrigin 注释添加到方法中,甚至添加到类控制器中以使其工作,但两者都没有方法不起作用。我还尝试在应用程序引导配置或实现WebMvcConfigurer 的类配置上创建Bean,但最终结果仍然相同。
起初我认为这可能是因为我使用ResponseEntity 实例返回响应,而不是像大多数示例显示的那样仅返回实际值,但即使替换了我返回值的方式,结果仍然相同。没有CORS 标头附加到响应中,即使在OPTIONS http 方法中,当它被请求时,它只响应没有Cross Origin Allow 的普通标头。
所以为了展示我一直在努力实现CORS,这是我的RestController 课程之一:
package com.vod.cloudservice.controller;
import com.vod.cloudservice.entity.Series;
import com.vod.cloudservice.service.SeriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/series")
public class SeriesController {
@Autowired
SeriesService seriesService;
@CrossOrigin
@GetMapping
public ResponseEntity<List<Series>> getSeriesList() {
List<Series> seriesList = this.seriesService.findAll();
return new ResponseEntity<>(seriesList, HttpStatus.OK);
}
// More resources ahead.
}
单独这样做是行不通的。所以我创建了一个这样的配置类:
package com.vod.cloudservice.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type")
.maxAge(3600);
}
}
即使这样,响应仍然相同。如果它有助于了解对我希望启用CORS 的控制器的完整请求,请求是这样完成的:
GET: http://localhost:8080/series
我可能通过拦截响应并手动添加标头来解决此问题,但我希望更好地控制响应,例如我想在一个类上处理 X 数量的允许方法。
【问题讨论】: