猿问

如何使用fetch在前端存储和处理JWT令牌,以及如何存储?

我是开发新手,我有一个任务管理器应用程序,我在其中使用 JWT 令牌进行验证,我可以让它在 Postman 上运行,但我不知道如何通过浏览器存储它并将它发送到服务器。


这是我试图让它工作的方法,但它在事件侦听器之外说未定义,我无法存储令牌以便稍后将其发送到另一个 url,我正在将令牌发送到 API。


这是我的前端 app.js 代码,用于登录页面,在登录时向用户发送一个 JWT 令牌:


let inMemoryToken;



const signInForm = document.querySelector( "#sign-in-form" );

signInForm.addEventListener( "submit", ( e ) => {

    const email = document.querySelector( "#login-email" ).value;

    const password = document.querySelector( "#login-pass" ).value;

    e.preventDefault();

    console.log( email, password );

    fetch( "http://localhost:3000/users/login", {

        method: 'post',

        headers: {

            'Accept': 'application/json, text/plain, */*',

            'Content-Type': 'application/json'

        },

        body: JSON.stringify( {


            "email": email,

            "password": password,


        } )

    } ).then( res => res.json() )

        .then( res => {

            console.log( res );

            let inMemoryToken = res.token;

            console.log( inMemoryToken );

            // { Authorization: `Bearer  ${ inMemoryToken }`; }

            return inMemoryToken;

        } );


    console.log( inMemoryToken );


    

 return inMemoryToken;

} );

// inMemoryToken = res.body.token[ 0 ];

// let inMemoryToken2 = inMemoryToken;


console.log( inMemoryToken );

我的登录后端代码是:


router.post( "/users/login", async ( req, res ) => {

    try {

        const user = await User.findByCredentials(

            req.body.email,

            req.body.password

        );

        const token = await user.generateAuthToken();

        res.send( {

            user,

            token,

        } );

    } catch ( e ) {

        res.status( 400 ).send( {

            error: "Catch error",

            e,

        } );

    }

} );


从 3 天开始,我一直在尝试解决这个问题,但无法正常工作,我们将不胜感激任何帮助。


陪伴而非守候
浏览 205回答 1
1回答

慕莱坞森

要在客户端上存储 JWT,您有两种选择:Cookies或LocalStorage策略。我想您已经知道什么是 cookie。LocalStorage 与 cookie 非常相似,但有所增强且不在标头中发送信息(请参阅Mozilla 开发人员定义),这就是 LocalStorage 通常用作持久对象的原因。服务器端保持不变。无需更改。在您的客户端上,在登录响应的处理程序中,您将在 LocalStorage 中存储来自后端的响应,如下所示:signInForm.addEventListener( "submit", ( e ) => {  . . .  fetch( "http://localhost:3000/users/login", {    . . .  } ).then( res => res.json() )       .then( res => {          console.log( res );          let inMemoryToken = res.token;          localStorage.setItem('user', JSON.stringify(res));          // 'user' is the generic key to sotre in LocalStorage. You could use any name you want          // Store complete object, so you will be able to access 'user' and 'token' later在你的任务功能上,你应该为你的对象阅读 LocalStorageconst TaskForm = document.querySelector( "#add-tasks" );TaskForm.addEventListener( "submit", ( e ) => {    const task = document.querySelector( '#task' ).value;    e.preventDefault();    console.log( task );        // ------ This is what you have to add --------    const localstorage_user = JSON.parse(localStorage.getItem('user'))    const inMemoryToken = localstorage_user.token    // -------------------------------------------    console.log( inMemoryToken );
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答