【问题标题】:How to send headers via Axios to a Spring-Boot application?如何通过 Axios 将标头发送到 Spring-Boot 应用程序?
【发布时间】:2018-10-24 08:09:18
【问题描述】:

我正在尝试使用 SpringBoot 和 Reactjs 制作一个 Web 应用程序。我在管理 JWT 时遇到问题。通过使用 Postman,我可以发送我的标题“jwt”并测试我的应用程序,它可以工作。但是当我通过 React 尝试使用

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);

            });

我无法从客户端接收任何标头“jwt”。 我处理来自客户端的请求的代码是:

    @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)
                }
}

我刚刚收到:

{
"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"
}

请问有什么建议吗?也许客户端需要授权才能发送标头?我被困住了。谢谢

【问题讨论】:

  • 我不认为 JWT 是 HTTP 标头。您可能必须在这里改变您的方法。你究竟想用 JWT 价值实现什么?
  • 我将“jwt”设置为自定义标题
  • 我正在尝试建立登录/注销会话
  • 这里有日志吗 System.out.println("我的jwt是:"+jwt); ?您还可以将 @RequestHeader 注释参数设置为 required=false
  • 我也试过了:我删除了 RequestParam 并使用 request.getHeader("jwt") 来获取它,但没有。也许我需要设置诸如 Access-Control-Allow-Credentials"、"Access-Control-Allow-Headers"、"Access-Control-Expose-Headers" 之类的东西??我不知道

标签: java reactjs spring-boot jwt axios


【解决方案1】:

我成功了。我必须创建一个 axios istance,现在它可以工作了。谢谢大家

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

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2017-06-21
    • 1970-01-01
    相关资源
    最近更新 更多