【问题标题】:HTTP post request error when trying to submit a form尝试提交表单时出现 HTTP 发布请求错误
【发布时间】:2021-01-01 08:55:49
【问题描述】:

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

【问题讨论】:

  • edit您的问题并将HTML代码以及错误消息添加为文本,而不是图像。
  • Turing85 是 CORS 问题,不需要 HTML 代码
  • @Masood 你能帮帮我吗
  • @kavx 我希望我可以,但我对 Java 一无所知。我在使用 PHP 时遇到了同样的问题。
  • 出于测试目的的临时解决方案,您可以安装 chrome 扩展 MOESIF。此扩展程序将允许绕过 CORS 并确保在浏览其他网站时将其关闭。

标签: java angular typescript crud httpservice


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你有一个@GetMapping,当你在发帖时,我认为你需要导入@PostMapping

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多