-2

angular service

  public extractUsername(token) {
    const headers = new HttpHeaders();
    headers.set('token', token);
    return this.http.get('http://localhost:8081/extractUsername', {headers});
  }

spring boot method

@GetMapping("/extractUsername")
public String extractUsername(@RequestBody(required=false) TokenRequest tokenRequest)  {
    String username = jwtUtil.extractUsername(tokenRequest.getToken());
    return username;
}

I cannot get token with this angular request

So my question is can i use requestbody method with get request? In postman it work as it should, if it is possible how should angular service look? Im new to angular thanks for response.

enter image description here

enter image description here

joachim
  • 45
  • 7
  • https://stackoverflow.com/questions/978061/http-get-with-request-body – lainatnavi Apr 17 '20 at 20:48
  • But when i make spring PostMapping and change get to post in angular, in postman it still works but when i try to access it with angular it is giving me same error – joachim Apr 17 '20 at 20:56
  • What is the error in developer console network tab ? – pc_coder Apr 17 '20 at 20:58
  • I have uploaded screenshot, and when i change it to postmapping it is giving same error but with this message "JWT String argument cannot be null or empty." – joachim Apr 17 '20 at 21:02

1 Answers1

2

On the Angular side, the header value is not being set. You need to assign the set or append result back to the variable:

const headers = new HttpHeaders().set('token', token); 

In the controller, you have to extract the header from the request. In Spring, you can do this by using the @RequestHeader annotation:

@GetMapping("/extractUsername")
public String extractUsername(@RequestHeader(value="token") String token)  {
    String username = jwtUtil.extractUsername(token);
    return username;
}

Alternatively, you could also inject HttpServletRequest into the method and extract it from the request:

@GetMapping("/extractUsername")
public String extractUsername(HttpServletRequest request)  {
    String username = jwtUtil.extractUsername(request.getHeader("token"));
    return username;
}
vox
  • 381
  • 1
  • 3