【发布时间】: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 阻止。
【问题讨论】: