angularrestspring-boot

Angular 7 post request with body and header


I am trying to do a post request with body and header. Below are some of the variations I have gone through, but for the most part I am getting error on the server saying that the parameter, 'key', was not passed in.

I tried this api in the postman and it's working there. This is how I have defined the method header in Java/Spring Boot:

@RequestMapping(value = "/getIssue", method = RequestMethod.POST)
public IssuePojo getIssue(@RequestParam("key") String key, HttpServletRequest request) {

Below are my angular's variations:

public getJiraIssue(key: string): Observable<any> {

    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.idToken });
    let options = { headers: headers };

    const paramsA = new URLSearchParams();
    paramsA.set('key', key);
    let params = new HttpParams().append('key', key);
    // return this.http.post(this.urlEnvironment.jiraGetIssue(), params, this.getHeaders());
    console.log("headers: ", this.getHeaders());
    // let obj = {
    //   key: key
    // }

    var headersA = new Headers();
    headers.append('Authorization', this.idToken);

    let body = new HttpParams()
    .set('key', key);

    return this.http.post(this.urlEnvironment.jiraGetIssue(), body, {headers: headers});
    // return this.http.post(this.urlEnvironment.jiraGetIssue(), null, {headers: this.getHeaders(), params: params});
  }

It seems that the body is being sent:

enter image description here

But this is the error I got:

timestamp: "2019-01-30T04:30:40.721+0000", status: 400, error: "Bad Request",…}
error: "Bad Request"
message: "Required String parameter 'key' is not present"
path: "/jira/getIssue"
status: 400
timestamp: "2019-01-30T04:30:40.721+0000"
trace: "org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'key' is not present

Solution

  • So the key is 'Content-Type': 'application/json', Since I'm sending json, then on the server side its expecting to map it to an Object. I managed to get it to work with string as well, but then I have to parse the string myself on the server which is not what I'm looking to do.

    So 'Content-Type': 'text/plain', => maps to => @RequestBody String key

    And 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', => maps to => @RequestParam String key, @RequestParam String test,

    And so the post call from Angular will look like this:

    const httpBody = new HttpParams()
          .set('key', 'key')
          .set('test', 'test');
        return this.http.post(endPoint, httpBody, this.getArgHeaders());
    
      private getArgHeaders(): any {
          const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            })
          };
          return httpOptions;
      }