问题
As you know, nuxtjs is server side rendering and there is no good example how to store data into localstorage which is client side.
My work is need to build login form where user can put username and password into the form the send it to server (via api) to check, if login data is correct, the api will return one token key then I will store this key to verify is user is authen and use it with other api.
I found some example but build with vuejs here https://auth0.com/blog/build-an-app-with-vuejs/ but I don't have an idea how to change it to nuxtjs.
Any I have read https://github.com/robinvdvleuten/vuex-persistedstate which I can plug in to my project but I would like to see other solution.
Regards.
回答1:
nuxtjs provides you with process.browser
to tell it to execute only on the client side
so use it like this:
methods:{
storeToken(token){
if(process.browser){
localStorage.setItem("authToken", token);
}
}
}
see this link for more info
回答2:
You can use process.browser
to check it's in browser or not.
export default {
created() {
this.storeToken();
},
methods:{
storeToken(token){
if(process.browser){
localStorage.setItem("authToken", token);
}
}
}
}
You also call this method in mounted without check process.browser
.
export default {
mounted() {
this.storeToken();
},
methods:{
storeToken(token){
localStorage.setItem("authToken", token);
}
}
}
回答3:
A little late to the party, but I was having similar problems.
But first I would recommend you to use cookies for saving a key/token/jwt. The reason being that localStorage can be hijacked through JS api's and cookies can be safeguarded from that. You will however have to safeguard your token from CSFR. That can be done by having a look at the Refence and Origin headers server side. This guy wrote a good post on how to do that: How to protect your HTTP Cookies
As for accessing localStorage from Nuxt, here we go:
If you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as:
Isomorphic application (server-side rendering + client-side navigation)
The result being that localStorage is not defined serverside and thus throws an error.
The give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.
if you want to read more about my solution you can find it here: localStorage versus Nuxt's modes
来源:https://stackoverflow.com/questions/47433168/how-to-store-data-to-local-storage-with-nuxt-js