M_Lude
M_Lude

Reputation: 365

How to send headers via Axios to a Spring-Boot application?

I'm trying to make a webapplication with SpringBoot and Reactjs. I'm having trouble managing the JWT. By using Postman I can send my header 'jwt' and test my app and it works. But when I try via React using

axios.get('URL/logout', { headers: { jwt: localvariable } } )
          .then(response => {
                console.log('Response of logout', response);
                this.setState({isLogged: false});
                console.log('Status after logout', this.state);

            })
            .catch(error => {
                console.log(error);

            });

i can't receive any header 'jwt' from the client side. My code which handle the request from client is:

    @CrossOrigin("*")

    @RestController
    public class LoginController {

        @RequestMapping("/logout")
            public ResponseEntity<JsonResponseBody> logoutUser(@RequestHeader(value="jwt") String jwt,HttpServletRequest request){
                   System.out.println("My jwt is: "+jwt);
                   return ResponseEntity.status(HttpStatus.OK)
                }
}

and I just receive:

{
"timestamp": 1526311750256,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.ServletRequestBindingException",
"message": "Missing request header 'jwt' for method parameter of type String",
"path": "/logout"
}

Please, any suggestion? Maybe the client needs authorizations to send headers? I'm stuck. Thank you

Upvotes: 2

Views: 1811

Answers (1)

M_Lude
M_Lude

Reputation: 365

I succeded. I had to create an axios istance and now it works. Thank you to everyone

let instance = axios.create();
instance.defaults.headers.common['jwt'] = this.state.jwt;
instance.get('URL/logout')
        .then(response => {
console.log('Response of logout', response);

});

Upvotes: 3

Related Questions