我已经创建了一个创建足球俱乐部和生成足球比赛的web应用程序,它的一个功能是当用户在GUI上输入随机日期时,程序应该显示当天进行的所有比赛。为此,我在HTML文件中创建了一个表单,并使用HTTP post请求将数据发送到位于另一个项目中的后端(2个不同的端口) localhost:4000-Angular GUI localhost:8082-Java Spring Boot应用程序(后端)
这是我的日期检查部分的代码!
-HTML文件
<div id="dateContainer"><form #datePost="ngForm" (ngSubmit)="onSubmit(datePost.value)" >
<input type="text" name="date" ngModel placeholder="12/12/2012">
<button type="submit">Find</button>
</form>
</div>
-Ts文件
import { Component, OnInit } from '@angular/core';
import{HttpClient, HttpClientModule} from '@angular/common/http';
@Component({
selector: 'app-date',
templateUrl: './date.component.html',
styleUrls: ['./date.component.css']
})
export class DateComponent implements OnInit {
onSubmit(data){
this.http.post('http://localhost:8082/dateReq',data)
.subscribe((result)=>{
console.warn("result",result)
})
}
constructor(private http:HttpClient) { }
ngOnInit(): void {
}
}
-Java
@CrossOrigin("http://localhost:4200")
@GetMapping("/dateReq")
public ArrayList<String> getDates(){
return PremiereLeagueManager.dateCheck;
}
当我在GUI中输入日期并单击查找按钮时,我在控制台上看到以下错误
Access to XMLHttpRequest at 'http://localhost:8082/dateReq' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
:8082/dateReq:1
Failed to load resource: net::ERR_FAILED
core.js:5967
ERROR HttpErrorResponse
defaultErrorLogger @ core.js:5967
发布于 2021-01-01 23:02:26
为什么在Java语言中有一个GetMapping,而在Angular中使用http.post?Get请求也没有参数。尝试在ts文件中进行更改:
onSubmit(数据){
this.http.post('http://localhost:8082/dateReq',data)
.subscribe((result)=>{
console.warn("result",result)
})
}
在java中:
@CrossOrigin("http://localhost:4200")
@PostMapping("/dateReq")
public ArrayList<String> getDates(){
return PremiereLeagueManager.dateCheck;
}
此外,我强烈建议您使用反应式表单,因为它们更好,您可以在此处查看详细信息:https://angular.io/guide/reactive-forms
发布于 2021-01-01 17:06:59
您有一个@GetMapping
,因为您正在写一篇文章,所以我认为您需要导入@PostMapping
https://stackoverflow.com/questions/65528413
复制相似问题