@CrossOrigin 不适用于 POST 方法

Posted

技术标签:

【中文标题】@CrossOrigin 不适用于 POST 方法【英文标题】:@CrossOrigin not working with POST method 【发布时间】:2021-11-04 16:17:56 【问题描述】:

您好,我正在开发一个网络应用程序。后端使用 Spring 运行,前端使用 React。如果我使用 POST Http 方法,我会遇到 CrossOrigin 的问题。 这是我的js代码:

const LOGIN_URL = "http://localhost:8080/auth/login";

login(username, password) 
return axios.post(LOGIN_URL, 
  username,
  password,
);

这里出现错误:

Access-Control-Allow-Origin 不允许来源 http://localhost:3000。 由于访问控制检查,XMLHttpRequest 无法加载 http://localhost:8080/auth/login。 加载资源失败:Access-Control-Allow-Origin 不允许 Origin http://localhost:3000。

Java Spring 示例代码:

@CrossOrigin(origins = "*")

@RestController
@RequestMapping("/auth")

public class AuthController 

 ...

@PostMapping("/login") 

public ResponseEntity<?> signInUser(@RequestBody LoginBody loginBody)

.....

 return ResponseEntity.ok("OK");


但是如果我使用 GET 请求,像这样:

JS代码:

  hello() 
return axios.get(HELLO_URL);

Java 代码:

@CrossOrigin
@RestController
@RequestMapping("public")
public class HelloWorld 

@GetMapping("/hello")
public String helloWorld() return "Hello ";


我没有错误。一切正常

你知道如何解决这个问题吗?

【问题讨论】:

【参考方案1】:

在 @PostMapping("/login") 注释之上添加 @CrossOrigin,而不是在类级别使用。

【讨论】:

以上是关于@CrossOrigin 不适用于 POST 方法的主要内容,如果未能解决你的问题,请参考以下文章