简体   繁体   中英

Angular 4 http POST request to java Spring Controller

Hello I want to send a string from my Angular 4 post request to my java spring mvc controller and return it's value.

in angular 4 function:

let body = 'example'

http
  .post('favourite', body)
  .subscribe(
      data => {
        console.log('favourite received');
      },
      error => {
        console.log('an error occured');
      }
    )

in my java code:

@RequestMapping(value= "/favourite", method = RequestMethod.POST)
@ResponseBody
public void createFavourite(@RequestParam(value="body") String favourite){
    Favourite.setFav(favourite);
}

Essentially I want to send just thestring: 'example' as the body and then receive it, again as a string in my java spring controller and set it for my Favourite fav value, so then if I have a Favourites.getFav() function in Favourite it will return "example". What am I doing wrong with the requestsand how can I make it work?

First of all you have to inject http, or httpClient. Second thing, why you have only 'favourite' in your post method? It is wrong. First param of every http method is full path like: http://localhost:8080/favourite

Here you have a lot of examples: https://angular.io/guide/http

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