无法从 Node 获取 cookie 到 React
Not able to get cookie from Node to React
我创建了一个简单的登录系统,在某些用户登录后端后,我使用 jwt 令牌值设置了配置文件 cookie
res.cookie('profile',jwt_token,{
secure : false,
httpOnly : true
});
在 React 前端中,我正在向 Node 后端发送一个获取请求,我希望从中获取该 jwt 令牌
const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});
这是我获取 cookie 的控制器
export const test = async (req,res) =>{
try {
const cookie = req.cookies.profile || "no cookie";
res.json(cookie);
} catch (error) {
console.log(error.message);
res.status(406).json({success:false});
}
};
当我在使用 Postman 登录后尝试获取 cookie 时,我得到了 cookie 值,但是当我尝试通过 axios 从 React 获取 cookie 时,我得到了 'no cookie'。我还在 Node
中设置了 app.use(cors())
显然存在一个已知的 Axios 错误,可以像这样解决。只需添加这行代码,然后重试。
axios.defaults.withCredentials = true;
const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});
您可能需要安装 cookie-parser
中间件 http://expressjs.com/en/resources/middleware/cookie-parser.html,然后将其添加到您的应用中:
const cookieParser = require('cookie-parser');
//...
app.use(cookieParser())
我创建了一个简单的登录系统,在某些用户登录后端后,我使用 jwt 令牌值设置了配置文件 cookie
res.cookie('profile',jwt_token,{
secure : false,
httpOnly : true
});
在 React 前端中,我正在向 Node 后端发送一个获取请求,我希望从中获取该 jwt 令牌
const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});
这是我获取 cookie 的控制器
export const test = async (req,res) =>{
try {
const cookie = req.cookies.profile || "no cookie";
res.json(cookie);
} catch (error) {
console.log(error.message);
res.status(406).json({success:false});
}
};
当我在使用 Postman 登录后尝试获取 cookie 时,我得到了 cookie 值,但是当我尝试通过 axios 从 React 获取 cookie 时,我得到了 'no cookie'。我还在 Node
中设置了 app.use(cors())显然存在一个已知的 Axios 错误,可以像这样解决。只需添加这行代码,然后重试。
axios.defaults.withCredentials = true;
const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});
您可能需要安装 cookie-parser
中间件 http://expressjs.com/en/resources/middleware/cookie-parser.html,然后将其添加到您的应用中:
const cookieParser = require('cookie-parser');
//...
app.use(cookieParser())