Javascript 使用 nodejs 保存到本地存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37182573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:00:12  来源:igfitidea点击:

Saving into local storage with nodejs

javascriptnode.jsexpresslocal-storage

提问by Paran0a

I need to save jwt-token in local-storage through nodejs after the user has logged in (has been authorized ).

我需要在用户登录(已授权)后通过 nodejs 将 jwt-token 保存在 local-storage 中。

After I check if the user/password is correct in my controller - I save generated token in local storage. As it stands I can't reference window as it doesn't exists.

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

ReferenceError: window is not defined 

This is how I'm currently trying to do it.

这就是我目前正在尝试这样做的方式。

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

回答by Sel?uk

You cannot save to localStorageon Node.js, but you can do it on a browser, possibly after sending from a server, for your case from a server on Node.js.

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

You should send the token from the server (running on Node.js) to the client (browser) which has a windowobject, having the localStorageand related getItemand setItemmethods, you can reference from your JavaScript code for client (browser). Node.js does not have any windowto reference. So, by referencing it in Node.js code you will get an undefinederror you have encountered.

你应该从发送服务器(上Node.js的运行),客户端(浏览器)的标记具有window对象,具有localStorage与相关getItemsetItem方法,你可以从你的JavaScript代码中引用的客户端(浏览器)。Node.js 没有任何window参考。因此,通过在 Node.js 代码中引用它,您会undefined遇到遇到的错误。

Just put it into a cookie and send, or send it via a json response. Then on the client browser save it into window.localStorage.

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

following is the examples code for the latter way; sending via a response:

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

// 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")
      })
  })

回答by Hardipsinh Jadeja

If you mean html 5 localStorage, there's no such a thing since node.js is a server-side technology. Html 5 localStorage is a client side feature supported

如果您的意思是 html 5 localStorage,则没有这样的事情,因为 node.js 是一种服务器端技术。Html 5 localStorage 是支持的客户端功能

refer How to access localStorage in node.js?

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

回答by user2331566

In the client call to /login use xmlhttpresponse object, then add an event listener for 'load'. This will give the client the responseObject where you have added the token. Then in the event listener put your localStorage code

在对 /login 的客户端调用中,使用 xmlhttpresponse 对象,然后为“load”添加一个事件侦听器。这将为客户端提供您添加令牌的 responseObject。然后在事件侦听器中放置您的 localStorage 代码