java 部分的代码
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
log.info("Adding CORS mappings");
registry.addMapping("/**") // 推荐限定路径前缀,而不是 /**
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Authorization", "Link", "X-Total-Count")
.allowCredentials(false)
.maxAge(3600);
}
}@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
@RestController
@RequestMapping("/count")
public class LaborHourCountController {
我还试了显示的处理 options 请求
@Slf4j
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
@RequestMapping("/laborOrder")
public class LaborOrderController {
@Resource
private LaborOrderService laborOrderService;
/**
* 查询工时工单列表
* */
@PostMapping(value = "/getLaborOrder/list")
public Result getLaborOrderList(@RequestBody LaborOrderVo laborOrderVo){
PageResult<LaborOrder> laborOrderList = laborOrderService.listByVo(laborOrderVo);
return Result.success(laborOrderList);
}
// 显式处理 OPTIONS 请求
@RequestMapping(value = "/getLaborOrder/list", method = RequestMethod.OPTIONS)
public ResponseEntity<?> handleOptions() {
return ResponseEntity.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
}
仍然浏览器显示
Access to XMLHttpRequest at 'http://xxx:8085/laborOrder/getLaborOrder/list' from origin 'http://xxxx:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这个 OPTIONS 需要满足
http 状态码需要 200
响应头需要包含 Access-Control-Allow-Origin * 和 Access-Control-Allow-Methods: *
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLlsLnmmZciLCJ1c2VySWQiOiIxNzEwOTA1MDQ5NTUyNiIsInBlcm1zIjpbXSwiYXZhdGFyIjoiaHR0cHM6Ly9zdGF0aWMtbGVnYWN5LmRpbmd0YSG1uMUFBXzcwN183MDcuanBnIiwidXNlck5hbWUiOiLlsLnmmZciLCJleHAiOjE3NTE1NDgzNDMsImlhdCI6MTc1MTUzMDM0M30.CeY0ER8LrElYGxMtYmz9DR_1jI84NRVh2Dq_FH3O_w5TQbhk8mJhIfrZIeor30YF7IURGzdUI8_ym6UNa_9Dcg
Content-Type: application/json
Referer: http://192.168.130.163:5173/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 dingtalk-win/1.0.0 nw(0.14.7) DingTalk(7.0.20-RC.5169101) Mojo/1.0.0 Native AppType(rc) Channel/201200 Architecture/x86_64