您无法在 Node.js 上保存到 localStorage,但您可以在浏览器上执行此操作,可能在从服务器发送之后,从 Node.js 上的服务器发送。
您应该将令牌从服务器(在 Node.js 上运行)发送到具有 window 对象、具有 localStorage 和相关的 getItem 和 setItem 方法的客户端(浏览器),您可以来自客户端(浏览器)的 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;
})