尝试提交表单时出现 HTTP post 请求错误

时间:2021-01-01 08:55:49

标签: java angular typescript crud httpservice

我创建了一个网络应用程序,用于创建足球俱乐部并生成足球比赛 它的一个功能是当用户在 GUI 上输入随机日期时,程序应该显示当天进行的所有比赛。 为此,我在 HTML 文件中创建了一个表单,并使用 HTTP post 请求将数据发送到另一个项目中的后端(2 个不同的端口) 本地主机: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

2 个答案:

答案 0 :(得分:0)

为什么在 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

答案 1 :(得分:-1)

你有一个 @GetMapping,当你在做一篇文章时,我认为你需要导入 @PostMapping