使用nodejs将数据保存到本地存储(localStorage)

10

用户登录成功(已经获得授权),我需要通过nodejs将jwt-token保存在本地存储中。

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

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
      });
...

5
你知道客户端和服务器之间的区别吗? - Amit
那么...你为什么要在服务器上尝试客户端的事情呢? - Amit
我在想是否有可能。我会引用其中一个链接主题中的人所说:“有很多模块可以将DOM带到服务器端,将webkit带到服务器端,因此我很好奇是否有人将localStorage带到了服务器端。” - Paran0a
你可以在客户端使用jQuery或AngularJS访问本地存储。因此,请将您的代码放在那里 :) - Hardipsinh Jadeja
1
嘿!@Paran0a。你能检查一下你问题的答案吗?我的可能是正确的:)) - sçuçu
3个回答

17

在 Node.js 上无法保存到 localStorage,但你可以在浏览器上保存,可能是从服务器发送后,在你的情况下从运行在 Node.js 上的服务器发送。

你应该将令牌从运行在 Node.js 上的服务器发送到具有 window 对象的客户端(浏览器),客户端具有相关的 localStoragegetItemsetItem 方法,你可以从你的 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;
  })

你好,你能给我一个例子如何通过JSON响应发送它吗? - Kannan T
嗨,兄弟,我之前已经解决了这个问题,谢谢你的帮助。但是我现在遇到了重定向页面的问题,你能帮我吗? - Kannan T
1
@kannan 如果您将令牌发送到请求中而没有使用cookie,那么请在客户端上进行重定向,并在上述代码行设置window.localStorage之后立即执行。否则,在重定向页面时会发生完整页面重新加载,从而丢失令牌和从服务器端发送的数据。要使您的网页在此设置操作后重定向,请使用window.location,只需将其分配给您要重定向到的地址,例如window.location.assign('http://example.com/') - sçuçu
现在您想让我在客户端进行更改以实现重定向,即前端登录代码,对吗? - Kannan T
也许我们应该把这个讨论移到聊天中,或者如果您能将您的问题/疑问识别为不同的问题,您可以在单独的SO问题中再次提出它,我会在那里回答以更好地使用SO。 - sçuçu
显示剩余3条评论

1
在客户端调用 /login 时使用 xmlhttpresponse 对象,然后为 'load' 添加事件侦听器。这将为客户端提供 responseObject,您可以在其中添加 token。然后在事件侦听器中放置您的 localStorage 代码。

1
如果你指的是html5 localStorage,那么在node.js这个服务器端技术中并不存在这样的东西。html5 localStorage是客户端的一个特性,被支持。
参考如何在node.js中访问localStorage?

是的,我在谈论那个存储。我看过一些教程,人们建议将生成的令牌保存到 cookie 或本地存储中。所以如果我想从 Node 中保存它,我应该使用 cookie 吗? - Paran0a
可以使用cookies来实现相同的功能。 - Hardipsinh Jadeja
你可以使用cookies或json响应。 - sçuçu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接