我遇到了一个问题,我无法从我的node.js后端抓取我的cookie。下面是我当前的代码,当我console.log(req.cookies)它返回[Object: null prototype]{}。我过去也遇到过类似的问题,我解决这个问题的方法就是添加"withCredentials: true"。但既然我已经在axios的帖子请求上有了这个,我不认为这是问题。
前端
const save = async () => {
if (loggedInCookie) {
await axios.post('http://localhost:5000/savelisting', {
withCredentials: true,
link: link,
car: car,
price: price,
picture: picture,
timeleft: timeleft,
site: site,
milage: milage,
location: location,
trans: trans
});
} else {
console.log("please login to save this listing")
};
};
后端>app.post('/savelisting', async (req, res) => {
console.log(req.cookies);
try {
var jwtToken = await req.cookies.AccessToken;
console.log(jwtToken);
// Grooms cookie
jwtToken = jwtToken
.split('; ')
.find(row => row.startsWith('AccessToken='))
.split('=')[1];
const decoded = jwt.verify(jwtToken, process.env.TOKEN_KEY);
var userId = decoded.id
console.log(userId)
const link = req.body.link;
const car = req.body.car;
const price = req.body.price;
const picture = req.body.picture;
const timeleft = req.body.timeleft;
const site = req.body.site;
const milage = req.body.milage;
const location = req.body.location;
const trans = req.body.trans;
} catch(err) {
console.log(err)
};
res.status(200).send();
});
您正在将withCredentials
设置作为数据的一部分发送到API。它应该作为一个选项传递给axios:
axios.post(
'http://localhost:5000/savelisting',
{
link: link,
car: car,
...
},
{
withCredentials: true
}
)