-1

I make an application with a spring server and angular for the client. I'm trying to make a post request and have this error:

Failed to load http://localhost:8080/statuts:

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 415."

I have followed the Spring tutoriel : https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-controller and nothing works for me.

As for my spring code I have put the cross origin annotation that works for all other request like get and put (if I delete this line the others request send exactly the same error)

@CrossOrigin(origins = "http://localhost:4200")
public class ExempleController {

    @PostMapping(path="", consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Exemple addExemple(HttpServletRequest request) throws IOException {
        Exemple exemple = new Exemple();
        Exemple updatedStatut = objectMapper.readerForUpdating(exemple).readValue(request.getReader());
        statutRepository.save(updatedExemple);
        return exemple;
    }

I also tried it with the global config but same issue

My request in angular :

create(exemple: Exemple){
    return this.http.post("localhost:8080/exemples", JSON.stringify(exemple));
}

Thanks you for your help

== Edit ==

I haven't mention it but my request is working as it works just fine with PostMan it is a communication problem between the client and the server

2 Answers2

0

I don't see the need of the @CrossOrigin annotation here, unless there is an specific reason you didn't mention.

About creating a POST WebService using Spring, you can follow this example:

    @RestController
    public class ExempleController {

    @RequestMapping(value = "/", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)

   public  @ResponseBody Exemple addExemple(@RequestBody LinkedHashMap map, HttpServletRequest request) throws IOException {

          // CODE HERE
        }

    }

*You can consider replacing LinkedHashMap by your DTO class, but this will work.

I hope it helps ;-)

Roberto Rodriguez
  • 3,179
  • 32
  • 31
  • With my client being with angular on the 4200 port I need to add the cross origin to be able to communicate with it. The probleme is not the POST that isn't working because it work just fine when I send the request with PostMan – Loïc Thierry May 16 '18 at 08:19
0

Well I found the answer The problem is in angular that doesn't send the headers in the post request that is needed.

so I changed my angular code into :

create(exemple: Exemple){
    const headers1 = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
    return this.http.post(this.ExempleAPI, JSON.stringify(exemple), {headers: headers1});
}

hopes it can help someone else