【问题标题】:fetch api call blocked by cors获取被 cors 阻止的 api 调用
【发布时间】:2020-10-27 00:54:49
【问题描述】:

我有一个 spring 服务器正在运行,通过观看 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))

}

但每当我通过 $(function() {.. 在 HTML 中运行上述脚本时,我都会收到一条错误消息

CORS 策略已阻止从源“null”访问“<...>”处的 XMLHttpRequest:仅协议方案支持跨源请求。 http、数据、chrome、chrome-extension、https。

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

我的弹簧控制器有

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

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

【问题讨论】:

    标签: jquery spring fetch-api


    【解决方案1】:

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

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

    【讨论】:

    • 它在做 file://C:...我不明白为什么它默认没有 http
    猜你喜欢
    • 2021-06-22
    • 2021-07-20
    • 2020-08-16
    • 2016-03-02
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2019-02-13
    • 2019-04-14
    相关资源
    最近更新 更多