fetch api 调用被 cors 阻止

fetch api call blocked by cors

我有一个 spring 服务器 运行ning 并且通过观看 tutoirals 教程我得到了一个简单的函数

registerUser() {

user = {
  firstname: this.firstname,
  lastname: this.lastname,
  email: this.email,
  //more fields
}

var h = new Headers({"Content-Type":"application/json"});,
fetch('/user', {method: "POST", headers: h, body: JSON.stringify(user)})
  .then(response => console.log(response))
  .catch(error => console,error("Error:", error))

}

但是每当我 运行 在 HTML 中通过 $(function() {..

Access to XMLHttpRequest at '<...>' from origin 'null' has been blocked by CORS policy: Cross-Origin requests are only supported for protocol schemes. http, data, chrome, chrome-extension, https.

我搜索了错误,在我看来我的 spring 应用程序不在 HTTP 上 运行,但是当我检查浏览器并尝试 http://localhost:8080/test 它工作正常服务器日志中收到的请求。

我的spring控制器有

@PostMapping("/user")
@CrossOrigin("*")
public void createUser(@RequestBody User user){}

我启用了所有带 * 的来源,为什么它仍然被 cors 阻止。

那是因为您学习的教程可能包含 Spring 应用提供的那些静态资源。您的调用脚本与 http://localhost:8080 的来源不同,所以

fetch('http://localhost:8080/user'...)