为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2022-12-09 17:16:13
我是开发新手,我有一个任务管理器应用程序,我在其中使用 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 天开始,我一直在尝试解决这个问题,但无法正常工作,我们将不胜感激任何帮助。
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

要在客户端上存储 JWT,您有两种选择:CookiesLocalStorage策略。我想您已经知道什么是 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

在你的任务功能上,你应该为你的对象阅读 LocalStorage


const 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 );


查看完整回答
反对 回复 2022-12-09
  • 1 回答
  • 0 关注
  • 245 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号