如何在React.js前端和Express.js后端之间发送值



我想把"cookieValue"发送到我的后端,但我不太确定如何发送,也没能在网上找到任何好的资源。

目前,当我试图将"cookieValue"发送到后端时,我不相信它真的有值。我还收到一条警告,说"cookieValue"已声明,但从未在我的"findCookie函数"中使用过。下面是我的当前代码,如有任何帮助,将不胜感激。

前端代码:

import axios from 'axios'
import { Outlet, Navigate } from "react-router";
import { useState } from 'react'
let backEndResponse = null

function SendCookie() {

const [cookieValue, setCookieValue] = useState("");
if (document.cookie != null) {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('Auth='))
.split('=')[1];

axios.post('http://localhost:5000/auth', {
cookieValue,
}).then(getBackEndResponse => {
return axios.get('http://localhost:5000/auth', { withCredentials: true }).then((res) => {
res.render(backEndResponse);
})
});
} else {
}
}

const useAuth = () => {
if (backEndResponse) {
const authorized = {loggedIn: true}
return authorized && authorized.loggedIn;
} else {
const authorized = {loggedIn: false}
return authorized && authorized.loggedIn;
}
};
const ProtectedRoutes = () => {
const isAuth = useAuth();
return isAuth ? <Outlet/> : <Navigate to="/login" />;
}
export default ProtectedRoutes

后端代码:

app.post('/auth', (req, res) => {
const authCookie = req.body.cookieValue
if (authCookie === result) {
backEndResponse = true
} else {
backEndResponse = false
}
});
app.get('/auth', (req, res) => {
res.render(backEndResponse)
});

Cookies来自您的后端,浏览器会自动将它们与任何后续请求一起发送回同一后端。您的后端可以作为res.cookies访问它们。您不需要为此编写任何额外的代码。

最新更新