I tried searching the web for a node module that can access the client's localStorage but wasn't able to find anything. Anyone know of one?
You can use :
node-localstorage npm module to use localStorage at the nodejs server side.
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
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
When the page loads, send a post that queries the contents of the client's localStorage.
Found this store
// Store current user
store.set('user', { name:'Marcus' })
// Get current user
store.get('user')
// Remove current user
store.remove('user')
// Clear all keys
store.clearAll()
// Loop over all stored values
store.each(function(value, key) {
console.log(key, '==', value)
})
LocalStorage is never accessible by the server. Ever. It would be a huge security issue.
If you need to send it to a server, then you have to have a client-side JS script which retrieves it, and then sends it to the server as part of an Ajax or POST request.
Cookies work well for when you need to pass small amounts of data regularly between server and client.
Databases on your server are best if you need to store data long-term.
For Node.js you can use HandyStorage, a fast and small npm package which behaves data like a state
Here's an example:
const HandyStorage = require('handy-storage');
const storage = new HandyStorage('./store.json');
storage.setState({
name: 'Alireza',
lastname: 'Sh',
friends: [
'Jane',
'John'
],
visited: storage.state.visited || 0
})
storage.setState({
visited: storage.state.visited + 1
})
It automatically changes the JSON file, just give it a try!
In the JS file you write this:
const LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
Also you need:
open new Terminal press Control + C (don't worry it's for clear not for copy) and type you'r file.js (for ex: server.js) and than type this: npm i node-localstorage (now you all set).
Well, I think some explanations are in handy, first of all, node JS and V8 are two different things and runs on different places. Browsers uses the v8 engine to run JS, node JS runs on servers and is v8 based, but it doesn't have everything that the browser does (like the window object). So you can't access the browser local storage from your server because it's running somewhere (browsers runs on the user machine) else, I think that you want a lib that works like local storage but in your node js serve, for that we have store -> https://www.npmjs.com/package/store.
I'm From 2022 and yet there is no way we can instantly get the browser's localStorage without using fetch or ajax to communicate to the server but if you use react or veu for instance they can access it. Because they are frontend base libraries and frameworks
We can not save to localStorage on Node.js.
Related
I have nodejs app using express module, i had been changes some images inside public folder but when i checked from users side still on the old images and when clear browser cache i get on new images , is there a command to make this automatically.
Have a look at Etag. If the content of the resource is not changed the server will not send it again. When it is, as in your case it will.
Looking at the express docs I see etag is an boolean option of the middleware function static.
express.static({etag: true})
Some background information about tags.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
I am very new to electron so I may be going about this all wrong.
We have a few web apps internally that are all working and I wanted to practice by building one of them into electron.
What I need to do is load our SSO login page within the app and then listen for a cookie/session to be created after authentication has been successful.
I am using a webview like so:
<div style="width:100%; height:100%">
<span class="loading loader" id="loading" name="loading"></span>
<webview class="ssologin" src="https://example.com/resources/ldap.php" autosize="on" style="min-width:755px; min-height:640px"></webview>
</div>
This loads the login page for ldap/sso. After I login, it would normally take you to the web application you were going to before you were re-routed to SSO do to not having a valid session.
I am trying to figure out how I can listen for a cookie/session so that I know that they have authenticated and we get a response back.
Essentially, I need this valid session in order to make future API calls in the app to endpoints so I want to try and use this existing authentication implementation without having to include other modules and mess with all that.
Any suggestions?
Just in case you didn't know: Electron does not currently recommend to use <webview>:
We currently recommend to not use the webview tag and to consider alternatives, like iframe, Electron's BrowserView, or an architecture that avoids embedded content altogether.
Cf https://electronjs.org/docs/api/webview-tag#warning
You probably need to set a partition on your <webview>:
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>
Sets the session used by the page. If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. if there is no persist: prefix, the page will use an in-memory session. By assigning the same partition, multiple pages can share the same session. If the partition is unset then default session of the app will be used.
Cf https://electronjs.org/docs/api/webview-tag#partition
With that you can (from the main process) access the cookie of the session:
const {session} = require('electron');
const sess = session.fromPartition('persist:foobar');
const cookies = sess.cookies;
Then you can listen for changed events on that cookie object:
Emitted when a cookie is changed because it was added, edited, removed, or expired.
cookies.on('change', () => {
// do something when your SSO cookie is set
});
Cf https://electronjs.org/docs/api/cookies#event-changed
I would like to expose a node.js server variable to the client. I am trying to get express-expose to work.
I am not sure how to initialise and use that library.
In the express-expose guide the usage doesn't make sense
var express = require('express');
var expose = require('express-expose');
app = expose(app);
app.expose(...);
how can I use app in 'expose(app') before it was initialised ?
I used
const app = expose(express());
app.expose('var some = "variable";','head');
but that doesn't seem to work either.
Can anyone supply me please with an example that initialises the express-expose library and exports var 'some' to the client ?
(By exposing to the client I mean it will be available to all my javascript files as a global variable so that I could do 'console.log(some);' and it would print its value)
Using Pug
Since you're using Express with Pug, you can just call the res.render function and give it the variable you want. Here's how to do that.
Let's say you have a template called index.pug, it may look like this:
html
head
title= title
body
h1= message
On your server, the code responsible for the rendering should look like this. In this case we're passing someVariable to the view that needs to be rendered.
const someVariable = 'hello world!';
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: someVariable })
})
A note on express-expose
The express-expose library is not maintained and hasn't been updated in 5 years. My advice would be to just render your variable as described previously or just use AJAX requests.
A note on using a global variable
I am using the 'pug' view engine. It is passed to the view but I want
it as a global javascript variable.
A better idea is to use Template Inheritence to create "generic layouts" and extend them as needed. Sharing a global variable with file you're rendering will not update it magically on the front-end if you're changing it in the back-end. Even if the variable is global.
If you want to reflect "real-time changes" you should look into Socket.io.
This seems like a code smell... But regardless, there are cleaner ways to do it.
If you want to expose a data object, that is, an object just containing keys and values, you could embed it in the rendered webpage, make it available via some API endpoint that the client can acquire via an AJAX request, or expose a raw Javascript file that can be included via <script> (or I guess script(...) in pug).
If you want to expose a more complex Javascript object, such as a class or an object with function definitions, you could expose the Javascript file and include it via script(...).
However, you should be very careful exposing a file used by the server. If there are any vulnerabilities, they are now public. If there are any hard-coded passwords (which shouldn't be in code anyway), they are now public. Anything in this file is now public, so if you do indeed want to do this, be very careful about what code gets into this now client-side file.
If you need more details on how this could work, please comment :)
Edit: Also be aware that using the embedded and include methods would not allow the variable to be updated on-the-fly. If you need the client to track any changes to the data as it changes on the server, you will want to use AJAX. This is the best method, in my opinion. It offers you the most flexibility.
Another edit: Judging by the issues on the express-expose project, it seems not well supported and maybe has security issues. For now, I would avoid it. Maybe at a later time, it will be helpful and secure.
If you want to expose a variable value to the client from server , that never changes or updates, you can simply add a hidden input field in your template and add the value of it
In your EJS template file this would look like
<% if (data) { %>
<input type="hidden" value="<%= data %>" id="myGlobal"/>
<% } %>
you must pass the data value in your res.render('template',{data:"hello"}) function to the template.
You can access this variable value from client using a simple document.getElementById("myGlobal").Again don't pass any sensitive information in hidden fields.
If you want to pass sensitive information , implement an endpoint in your server with authentication and call the endpoint from client via an ajax call .This is also a best approach to update the value of the variable from client side.
I'm trying to build my app with React and Node (Isomorphic Rendering Architecture). I found on github example project but i have problem. I would like to develop my project client and server together, that the same Component can gets data/actions whataever from client nad server simultaneously. For example:
var Component = React.createClass({
render: function() {
return (
<div className="commentBox">
{this.props.client}
{this.props.server}
</div>
);
}
});
You can see that, Component gets props from client and server together. How i can do this?
I tryed 3 github projects but always i can't implement it. I dont know why. of course it's working when i render Component only by server or only by client but it's not working together.
For example when I render Component by server i can't make any actions specific for client (onclick alerting etc.) . So that's why it's important for me. Rendering some data from server and makes some client actions. But together, still on the same Component.
I'm sorry for my poor english!
Jan, it's impossible to do this using React.
They don't work "at the same time".
The server-side React code works by building the HTML page as a text-string, and serving the HTML text to the client.
After the browser loads the page, the React code in the browser will attach itself to the React code that was put on the page (because the server prints out IDs for all of the components, for the browser to attach to, after).
The goal, then, is to feed data to components, instead of expecting to have access to both the browser and the server at the same time.
That way, you can use server-side code to get data for the component, and you can use client-side code to get data for the component, and the component won't care.
This is not quite valid React, or the right way to do JS, in general but have a look:
class ServerElement {
render ( ) {
// sync calls should rarely ever (ideally never, other than booting up) be used
var articles = db.syncGetArticles();
return <Articles articles={ articles } />;
}
}
class BrowserElement {
render ( ) {
// isn't real, and should never be used even if it was
var articles = ajax.sync("GET", "/articles");
return <Articles articles={ articles } />;
}
}
The important part here is not the Server or Browser element (like I said, that's not really going to work), but rather that the <Articles /> element isn't expecting a server or a browser; it's expecting a list of articles.
The benefit of this approach, then, is that the server builds the HTML, but before the page is served, it's pre-filled with data, which will later be updated (replaced or added to) on the browser.
I hope that helps; if it doesn't, ask away, and I'll try to add to the answer.
#Norguard Thank you for your comprehensive answer. I am trying to own your answer. I know that your example code is not valid for React/JS cuz we have to build our db actions in models area. But one thing puzzles me. We are sending API with our '/articles' and gets data from this. OK, its cool, but this is still public data. I wonder about the private data. How to use React Isomorphic to get specific data or server if/else condition to build better app.
If we are using client-side templating language (like ejs) it's very easy. We are building our .html file and injection server methods(or whatever) to specific tags for templating language. How do to the same in React server? I can't imagines this using components and server.
I think that I understand idea you showed me but need time to efficiently build Isomorphic app using React.
I am a nodejs newbie and would like to understand the navigation flow when using nodejs to serve mobile applications.
Moible app
index.html
Show all users
Nodejs server snippit
var myData = {
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
};
res.send(myData);
Question: how do I display this data on another page (users.html)? I've worked with nodejs where I can just render to a specific path and it picks the appropriate Jade file but not sure how to do it since the html / js files are on the phone and not the server.
If you know of an example application I can just look through that code and figure it out.
Thanks for your help.
First of all you need to understand that your node.js is executed on server side, and all it can do - response on requests and do some logic, that stays on the server.
Then there is .html and .js that is sent to your clients (browser), and it is rendered and executed on client-side. This execution and logic is very different, and is focused to provide user interactions and render all sorts of data.
So all you need is be able to 'ask' server for data (request) and then get response, validate it in browser, if it is valid, you can render it using JS.
In order to make your life easier, consider using jQuery.
AJAX - to make requests to server and get response with data.
express.js - web framework for node, helps with routes.
And just generally - go and try things, experiment and it is better to understand whole picture or specific details frist, before you making any decisions.