无法在浏览器的Cookie中存储JSON Web令牌 [英] Not able to store json web token in cookies in my browser

查看:81
本文介绍了无法在浏览器的Cookie中存储JSON Web令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在学习使用cors npm在MERN项目中进行用户登录的JWT身份验证.我能够生成jwt并将其存储在数据库中,但是我无法看到cookie被存储在浏览器.

So i was learning about JWT authentication for user login in MERN project using cors npm.I am able to generate the jwt and also able to store it in the DB , but i am not able to see my cookie being stored in the browser.

这是快递服务器中架构文件中存在的我的generateAuthToken()函数,在这里,我正在生成jwt&返回它-

This is my generateAuthToken() function present in the schema file in express server, here i am generating a jwt & returning it -

userSchema.methods.generateAuthToken = async function(){
try{
        //generate token
        const token = jwt.sign({_id:this._id.toString()} , process.env.SECRET_KEY);
        
        //stored the generated token in our document
        this.tokens = this.tokens.concat({token : token});

        //saved the changes made in the document
        await this.save();

        //returning the token generated when called
        return token;

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

}

并在Express服务器中存在的index.js中调用generateAuthtoken()函数.返回的令牌存储在'token'-

and calling the generateAuthtoken() function in the index.js present in express server.The returned token is stored in the 'token' -

const token = await userLogin.generateAuthToken();
        //console.log(token);


    //storing logged in tokens inside cookies
        res.cookie("logintoken" , token , {
            expires : new Date(Date.now() + 60000), //60sec from the time we store the token inside the cookie
            httpOnly : true
        });

在前端反应代码中,我正在fetch api中发送一个凭据标头,该标头调用存在于我的Express服务器端口4000上的登录路由-

And in the frontend react code , i am sending a credentials header inside fetch api , which calls to login route present in my express server at port 4000 -

const response = await fetch('http://localhost:4000/login',{
                method : "POST",
                credentials: 'include',
                headers : {
                    "Content-Type" : "application/json"
                },
                body : JSON.stringify({
                        email : email,
                        password : password
                })
        });

我在快速服务器中将cors npm软件包用于跨区域请求-

I am using cors npm package for cross-region requests in my express server -

   const cors = require('cors');

   app.use(cors());

在我的浏览器控制台中,我遇到此错误-

And in my browser console ,i am facing this error -

但是当我在浏览器中签到时,cookie不会存储在存储中-

but when i check in my browser , cookie is not getting stored in the storage -

总而言之,我正在生成一个jwt并将其返回到函数中.然后将返回的令牌存储在名为'logintoken'的cookie中.但是该cookie不会存储在浏览器中.

To summarise , i am generating a jwt and returning it inside the function.Then storing that returned token inside a cookie named 'logintoken'.But that cookie is not getting stored in the browser.

我正在对此进行研究,并能够找到一些线程来说明我们还必须在cors中定义一些标头,以便浏览器能够存储cookie.但是我也无法弄清楚如何添加作为实现此功能所需的标头.我之前曾使用过Cookie&jwt,但这是我第一次学习react,express&cors npm.谢谢您的回复.

I was researching on this and was able to find some threads stating that we also have to define some headers in cors so that the browser is able to store the cookie.But i was not able to figure out how to add as well as which headers are required to achieve this.I have worked before with cookies & jwt , but this is my first time learning with react , express & cors npm.Thank you for your response.

推荐答案

这是我当前应用程序中的代码段

here is a code snippet from my current app

app.use(
    cors({
        credentials: true,
        origin: `http://${process.env.REACT_APP_SERVER_HOST}:${process.env.PORT}`,
    })
);

这篇关于无法在浏览器的Cookie中存储JSON Web令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆