使用nodejs保存到localStorage



用户登录(已授权)后,我需要通过nodejs将jwt令牌保存在本地存储中。

在我检查控制器中的用户/密码是否正确后,我将生成的令牌保存在本地存储中。就目前情况来看,我无法引用窗口,因为它不存在。

ReferenceError: window is not defined 

这就是我目前尝试的方式。

...
      payload = {
        sub: user.email,
        role: user.role
      };
      token = jwt.sign(payload, jwtSecretKey, {expiresIn: '60m'});
      window.localStorage.setItem('token', token);
      res.status(200).render('index' , {
        user: user,
        token: token
      });
...

你不能在Node.js上保存到localStorage,但你可以在浏览器上保存,可能是从服务器发送之后,从Node.js的服务器发送。

您应该将令牌从服务器(运行在Node.js上)发送到客户端(浏览器),该客户端有一个window对象,具有localStorage和相关的getItemsetItem方法,您可以从客户端的JavaScript代码中引用。Node.js没有任何可引用的window。因此,在Node.js代码中引用它是一个ReferenceError,暗示程序代码引用的是一个未定义的东西,undefined

只需将其放入cookie并发送,或者通过json响应发送即可。然后在客户端浏览器上将其保存到window.localStorage中。

以下是后一种方式的示例代码;通过响应发送:

// SERVER-SIDE Code
// say `app` is your app server on node.js
// this is a url handler on your server-side code
// you just have sent your user credentials from a browser
// typically via a form in the body of your http request
app.post('/auth', function (req, res) {
  // you may have here some jwt token creation things
  // ...
  // and send it as your response to the client (probably a web browser) ..
  // with your prefrred name as the key, say 'my_token', ..
  // where you will save it to localStorage (ie. window.localStorage)
  res.json({my_token: 'asdfgh-anything-jw-token-qwerty'})
})

  // CLIENT-SIDE Code (may be a web browser)
  // You have just sent a request to the server..
  // ..with user credentials for authentication in the request body
  // in the request body may be a window.FormData object or a json etc.
  http.post('auth', userCredentials)
    // probably the request mechanism you make http..
    // ..requests asynchronously, maybe using a library,..
    // ..will return a Promise, and you will have a similar code below.
    .then(response => response.json())
    .then(responseJson => {
      // set localStorage with your preferred name,..
      // ..say 'my_token', and the value sent by server
      window.localStorage.setItem('my_token', responseJson.my_token)
      // you may also want to redirect after you have saved localStorage:
      // window.location.assign("http://www.example.org")
      // you may even want to return responseJson or something else or assign it to some variable
      // return responseJson;
  })

如果你指的是html 5 localStorage,那么就没有这样的东西了,因为node.js是一种服务器端技术。Html 5 localStorage是支持的客户端功能

请参阅如何在node.js中访问localStorage?

在对/login的客户端调用中,使用xmlhttpresponse对象,然后为"load"添加一个事件侦听器。这将为客户端提供添加了令牌的responseObject。然后在事件监听器中放入您的本地存储代码

最新更新