gpt4 book ai didi

java - Spring Boot 和 @CrossOrigin 仅带有 POST 注释

转载 作者:行者123 更新时间:2023-11-30 07:19:15 27 4
gpt4 key购买 nike

我有以下类(class)

@RestController
@RequestMapping("/bets")
@CrossOrigin
public class BetRestController {

@Autowired
private BetController betController;

@ResponseBody
@RequestMapping(method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public BetResource betOnGame(@RequestBody @Valid BetResource betResource) {
return BetTranslator.from(betController.betOnGame(BetTranslator.from(betResource)));
}

@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public List<BetResource> getAllBets() {
return betController.getAllBets().stream().map(BetTranslator::from).collect(Collectors.toList());
}
}

问题是,当我尝试访问 POST 方法时,我得到:

XMLHttpRequest 无法加载 http://localhost:8080/bets 。产地 http://localhost:3000 Access-Control-Allow-Origin 不允许。

但是 GET 方法有效。

我的配置有什么问题,或者 @CrossOrigin 注释处理中可能存在错误?!

最佳答案

如果我正确理解您的问题,则可以在一种特定方法上指定 CORS 来源。

Sprint Boot 文档:https://spring.io/guides/gs/rest-service-cors/

Enabling CORS

Controller method CORS configuration

So that the RESTful web service will include CORS access control headers in its response, you just have to add a @CrossOrigin annotation to the handler method:

这是来自 Spring boot 网站的示例:

@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

关于java - Spring Boot 和 @CrossOrigin 仅带有 POST 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37861146/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com