【发布时间】:2020-11-18 06:39:55
【问题描述】:
我正在尝试从 angular 到 spring 提出一个简单的请求。我使用了裸骨弹簧网和弹簧安全性以及简单的 angular(9) 请求。
让我分享一下我的 Java 和 Angular 代码。
Java 代码
@RestController @CrossOrigin(origins = "http://localhost:4200")
public class Main {
@RequestMapping("/hello")
public Map<String,Object> home(){
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello from Backend");
return model;
}
}
Angular 端 auth.componen.ts 文件
import { HttpClient } from '@angular/common/http';
import { NgForm } from '@angular/forms';
import { Component } from '@angular/core';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html'
})
export class AuthComponent{
isLoginMode = true;
title = 'Demo';
greeting = {};
onSwitchMode(){
this.isLoginMode = !this.isLoginMode;
}
onSubmit(form: NgForm){
console.log(form.value);
form.reset();
}
constructor(private http: HttpClient){
http.get('http://localhost:8080/hello').subscribe(data => this.greeting = data);
}
}
HTML 方面
<div style="text-align:center"class="container">
<h1>
Welcome {{title}}!
</h1>
<div class="container">
<p>Id: <span>{{greeting.id}}</span></p>
<p>Message: <span>{{greeting.content}}!</span></p>
</div>
</div>
我正在关注this link,但每次我收到此错误时:
编辑 1: Chrome 开发者工具 Network 标签结果:
我试图在网上搜索,但找不到答案。你能帮我继续吗?
【问题讨论】:
-
我看到您启用了带有注释的 cors。只是为了确保您的 Angular 应用程序在 localhost:4200 上运行?
-
你好 @CezaryButler 是的,我的 Angular 应用程序在 localhost:4200 上运行,我的请求页面是 localhost:4200/auth
-
您能否发布带有预检请求的 Chrome 网络标签的一部分?尽管存在注释,但似乎弹簧没有添加
Access-Control-Allow-Origin标头。 -
我编辑了我的问题。
标签: spring spring-mvc spring-security cors angular9