简体   繁体   中英

HTTP post request error when trying to submit a form

I've created a web application which creates football clubs and generates football matches One function of it is when the user enters a random date on the GUI, the program should display all the matches played in that day. For that I've created a form in my HTML file and using HTTP post request I want to send data to the my back end which is in another project (2 different ports) localhost:4000-Angular GUI localhost:8082-Java Spring Boot application (back-end)

Here is my code for the date check section!

----HTML file-----

<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 file----

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;

}

When I enter a date in my GUI and click on find button I get these errors on my console

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

Why do you have in Java a GetMapping and in Angular you use http.post?Get request don't have parameters,also. Try to change in your ts file:

onSubmit(data){

this.http.post('http://localhost:8082/dateReq',data)

.subscribe((result)=>{

  console.warn("result",result)

})

}

and in java:

@CrossOrigin("http://localhost:4200")

@PostMapping("/dateReq")

public ArrayList<String> getDates(){

    return PremiereLeagueManager.dateCheck;

}

Also, I highly recommend you to use reactive forms because they are better, you can see details here: https://angular.io/guide/reactive-forms

you have a @GetMapping and as you are doing a post I think you need to import @PostMapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM