最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to manage token expiration when adding "credentials: include" at React api requests - Stack Over

programmeradmin5浏览0评论

I recently discovered that using credentials: "include" successfully prevents the cookie from being accessed by JavaScript, and it works as expected. However, I encountered an issue where, upon JWT session expiration, the backend returns a 401 Unauthorized error. While a 401 error is commonly used for authentication issues, it may not be the most ideal way to handle token expiration. This is because a 401 error could also result from role-based access restrictions, which would make redirecting to the /login page inappropriate in such cases. Therefore, a more refined approach is needed to distinguish between these scenarios and handle them accordingly.

I'm using React as Frontend and Spring as Backend

Below is one such request:

 const handleLoginRequest = async (e) => {
    
    try {
      
      const response = await fetch('http://localhost:3000/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-XSRF-TOKEN': csrfToken || "",
        },
        body: JSON.stringify(formData),
        credentials: 'include'
      });
      console.log(response)
      const data=await response.json()
      console.log(data)

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Login failed');
      }
      console.log('Login successful!');

    } catch (err) {
      setError(err.message);
    }
  };

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论