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.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.