护照"/>
在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小时内删除。
发布评论