0

I want try do a Post request from my frontend (Angular 2) to my backend (Spring). But I can't.

The error:

GET http://localhost:8080/loginPost 405 ()

Failed to load http://localhost:8080/loginPost: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.190:4200' is therefore not allowed access. The response had HTTP status code 405.

My Angular Service:

import {Injectable} from "@angular/core";
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Login } from'../data-login/models/login.model';

@Injectable()
export class LoginService{


private loginUrl = 'http://localhost:8080/loginPost';  // URL to web API
private headers = new Headers({'Content-Type': 'application/json'});

constructor(private http: Http){}

 loginQuery(login: Login){
   console.log(login.id);
   return this.http.request(this.loginUrl,JSON.stringify(login));
 }
}

My Spring Backend Code:

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginProvider {

   @CrossOrigin(origins = "http://192.168.0.190:4200")
   @PostMapping(value="/loginPost", consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
   public ResponseEntity<?> verifyLogin(@RequestBody String maoe){
       System.out.println(maoe);
       return new ResponseEntity<>(HttpStatus.OK);
   }

}

I need to read the Json sent by my frontend, checking and responding with OK, no problems. But I can not read Json. I'm trying to store it in the variable "maoe"

Lucas Alves
  • 23
  • 1
  • 9
  • Please post the actual error, not a screenshot of it (some of us have proxies that don't allow imgur) –  Feb 14 '18 at 12:29
  • zone.js:2935 GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.190:4200' is therefore not allowed access. The response had HTTP status code 405. – Lucas Alves Feb 14 '18 at 12:32
  • Well it's a CORS issue. **[Find more information here](https://spring.io/guides/gs/rest-service-cors/)** –  Feb 14 '18 at 12:32
  • https://stackoverflow.com/a/39715785/4078143 – mxr7350 Feb 14 '18 at 12:35
  • my friends. the problem isn't the connection. I can't read the Json text send from my frontend. But I don't read this. I can response my frontend with OK – Lucas Alves Feb 14 '18 at 12:44
  • But error which have posted says it is **CORS** issue. – Jayesh Choudhary Feb 14 '18 at 12:47

1 Answers1

1

You are trying to do send a GET request to a resource that accepts only POST requests. That is why you are getting a 405 response. Change either your rest service or angular http service to have both matching request types.

mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52