在React中检查登录状态时出现401错误。后台使用快递、护照

编程入门 行业动态 更新时间:2024-10-03 14:31:00

在React中检查登录状态时出现401错误。后台使用快递、<a href=https://www.elefans.com/category/jswz/34/1771380.html style=护照"/>

在React中检查登录状态时出现401错误。后台使用快递、护照

我的注册请求工作得很好,所以我知道前端和后端连接正确。

我的前端代码如下所示: 我还尝试将 axios.get 请求放在 useEffect 挂钩中检查登录,但得到了相同的错误 401。

const handleLogin = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.post('http://localhost:5000/login', loginForm);
            console.log(response.data);
            setLoginForm({
                username: '',
                password: ''
            })
            const response2 = await axios.get('http://localhost:5000/check-login', {withCredentials: true});
            console.log(response2.data);
            setIsLoggedIn(response.data.loggedIn);

        } catch (err) {
            console.log(err);
        }
      }

我的后端代码如下所示:

app.get('/check-login', (req, res) => {
  if (req.isAuthenticated()) {
    console.log("Is Authenticated?", req.isAuthenticated());
    res.status(200).json({message: 'User is Logged in'});
  } else {
    res.status(401).json({message: 'User is not logged in'});
  }
})

当我发出 get 请求以使用邮递员检查登录时,它似乎工作正常。 只有当我尝试通过 React 应用程序登录时,才会出现 401 错误。这是完整的错误:

GET http://localhost:5000/check-login 401(未经授权) 处理检查登录

Axios错误

{message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
: 
"ERR_BAD_REQUEST"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Request failed with status code 401"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
: 
{data: {…}, status: 401, statusText: 'Unauthorized', headers: AxiosHeaders, config: {…}, …}
stack
: 
"AxiosError: Request failed with status code 401\n  

这是我的 cors 设置:

const cors = require('cors');

app.use(cors({
  origin: "http://localhost:5173",
  methods: "GET,PUT,POST,DELETE",
  credentials: true,
}));
回答如下:

更多推荐

在React中检查登录状态时出现401错误。后台使用快递、护照

本文发布于:2024-05-31 06:50:04,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:护照   后台   快递   状态   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!