【问题标题】:415 Unsupported media type on frontend React.js415 前端 React.js 上不支持的媒体类型
【发布时间】:2020-11-25 16:27:18
【问题描述】:

我正在开发一个全栈 Web 应用程序,使用 React.js 作为前端,Jersey v2.+ 作为后端。我正在使用 JWT 开发用户身份验证。我在后端有一个用于验证 JWT(如果用户通过身份验证)的 POST 方法,如下所示:

@POST
@Path("/profiles/tokenIsValid")
@Produces(MediaType.APPLICATION_JSON)
public Response checkTokenIsValid(ContainerRequestContext requestContext){
    try{
        Key key = keyGenerator.generateKey();

        String token = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        if(token == null){
            return Response.ok(false).build();
        }
        Jws<Claims> verified = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        if(verified == null){
            return Response.ok(false).build();
        }
        String username = verified.getBody().getSubject();
        User verifyUser = authenticate(username);
        if(verifyUser == null){
            return Response.ok(false).build();
        }
        return Response.ok(true).build();
    }catch(Exception e){
        return Response.status(500, e.getMessage()).build();
    }
}

当使用邮递员进行验证时,一切都按预期工作,授权标头中包含登录用户的令牌。如果令牌有效,则返回 true,否则返回 false..

在 App 功能组件的前端,我使用 useEffect 挂钩来检查令牌是否存在。

 useEffect(() => {
const checkLoggedIn = async () => {
  let token = localStorage.getItem("auth-token");
  console.log(token);
  if (token === null) {
    localStorage.setItem("auth-token", "");
    token = "";
  }
  const tokenRes = await Axios.post("/profiles/tokenIsValid",
  null,
  {headers: {"Authorization": token}}
  );
  console.log(tokenRes.data);
 
};

checkLoggedIn(); }, []);

似乎由于 Axios.post 请求而出现故障。当尝试在后端进行调试同时在前端刷新页面时,什么都没有发生,看起来好像没有对指定路径发出请求。另外,我在 package.json 中使用代理到后端路径,所以我不需要指定整个路径。

这是我在刷新页面时遇到的错误。

【问题讨论】:

    标签: reactjs jwt react-hooks jersey jersey-2.0


    【解决方案1】:

    如果您的资源方法中有一个没有任何注释的参数,则假定它是请求的主体。当然 ContainerRequestContext 不是正文。由于您只需要一个标头,因此我只需删除请求上下文参数并使用@HeaderParam("Authorization") String auth 参数即可。

    仅供参考:您收到 415 Media Type Not Supported 错误,因为内容类型设置为 application/x-www-form-urlencoded 并且正文参数是 ContainerRequestContext。我敢肯定,如果您查看服务器日志,您会看到一条异常消息,例如:A MessageBodyReader is not found for type application/x-www-form-urlencoded and Java type ContainerRequestContext。

    【讨论】:

    • 谢谢你的回答,我会考虑的。虽然我通过在 axios 方法的标头中将 Content-Type 指定为 'application/json' 从前端解决了问题。
    猜你喜欢
    • 2021-05-20
    • 2014-05-10
    • 2019-05-01
    • 2017-06-30
    • 2017-07-05
    • 2016-11-26
    • 2015-08-21
    相关资源
    最近更新 更多