I'd like to transmit a variable to another page with Node, in order to use it in the other page, I tried localstorage and defining a global variable, but no result for the moment, it says that node can't access the localstorage of the window :
test.js
var express = require('express')
var session = require('express-session')
var app = express()
app.post('/test1.html', function(req, res){
var user = "Jonhy DEEPPP";
console.log(user);
res.render( 'test1.html', { user:user } );
});
test1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Titre</title>
</head>
<body>
<script>
alert(user);
</script>
</body>
</html>
Related
sorry for this very basic question.
So I want to know how to make buttons responsive.
I have a client.js and index.html as shown below
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("myButton");
el.addEventListener("click", modifyText, false);
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
<button id="myButton">Click Me!</button>
When I run on codepen it works fine.
But when I try to run these locally, with a server.js like this
console.log('Server-side code running');
const express = require('express');
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
and I change the html into having a script calling the client.js
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example-1</title>
</head>
<body>
<button id="myButton">Click me!</button>
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
<script src="client.js"></script>
</table>
</body>
</html>
Then I run node server.js and I type localhost:8080 in my browser, the html file gets displayed but when I click the button, it doesn't cause any number changes.
How can I get these to work for real?
Also, ultimately I want the node.js server side to know a button has been pressed. Maybe print on the node.js console that "a button was pressed", whenever it was done on my browser. How can I achieve that?
What I want is to pass information from client side to server side easily but I am quite confused with how to do that and many people suggest different ways.
Edit:
Aligned file names.
I have node js running a server that loads an html file with express. This html file has javascript that hides and shows a picture on the page with a button. I want to use the same function to hide and show the picture without the need for a button by calling the method in the main.js file that contains the rest of the application code. However, whenever I call the method it gives me a document not defined error. The button that calls the same function when clicked works however. I am not sure what the problem is (new to node).
web.js:
const hider = require("./public/script");
function site(){
const express = require('express');
const path = require('path');
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => console.log("Server Started on: 127.0.0.1:"+port));
};
function hidePic(){
hider.hide();
}
module.exports = { site , hidePic}
File loaded by express. The button to hide the image works.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="hide()">Try it</button>
<div id="picture1">
<img src="img.jpg" alt="img">
</div>
<script src="script.js"></script>
</body>
</html>
script.js:
function hide() {
var x = document.getElementById("picture1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
module.exports = { hide }
Main program
main.js:
const web = require("./website")
web.site();
web.hidePic(); //Want this to hide picture in on webserver from within this file
I want to test the new Firefox Storage Access API to allow 1st party storage (cookie, local storage, indexeddb, ...) to an iframe of a different domain (but still under my control).
Parent Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://child.local:8080/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
</script>
</body>
</html>
Child Iframe Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
When clicking on the "Login" button from the Child Iframe, the following log output is generated:
no access - requesting access # iframe-firefox.html:22:25
hasAccess: true # iframe-firefox.html:27:25
Request to access cookie or storage on “http://child.local:8080/iframe-firefox.html” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. # iframe-firefox.html:28:24
The visible conclusion is:
The promise document.hasStorageAccess() resolves
The hasAccess parameter is initially 'false'
The promise of document.requestStorageAccess() is returned and resolves
The 2nd promise document.hasStorageAccess() resolves
The hasAccess parameter is now 'true'
nevertheless, simple storage access to local storage is not possible.
What do I do wrong?
More Info's:
Firefox Developer Edition Version 65.0b9
Content Blocking Setting:
This seems to be a bug in the version of Firefox you're using. I set up a test locally of what you have and in Firefox 69.0.1 (64 bit), I get no error and the value is stored to local storage. When I took the sandbox flag allow-storage-access-by-user-activation out of the parent iframe, the child failed to get permission for local storage, so that confirms that my setup was actually working properly. Here's what I did:
Created a Node.js/Express server for the parent:
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8080, function() {
console.log('listening on *:8080');
});
Created a Node.js/Express server for the child (with different port to trigger same origin policy):
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8081, function() {
console.log('listening on *:8081');
});
Created an index.html for the parent (pretty much the same as yours):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://127.0.0.1:8081/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
// Added this to try out the JSChannel
chan.call({
method: "reverse",
params: "hello world!",
success: function(v) {
console.log(v);
}
});
</script>
</body>
</html>
And created iframe-firefox.html for the child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
// Other end of the JSChannel call
chan.bind("reverse", function(trans, s) {
return s.split("").reverse().join("");
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
And everything worked as expected... So I'm feeling pretty sure that the issue is with the specific version of Firefox Developer Edition that you're using.
Also, here's a link to a zip of my setup if you want to give it a try on your end and see if this works differently than what you have: server.zip
Let me know if there's anything else I can do to help.
im very new to Angular.js and i cant seem to get my expression to display the values from my controller, it just sees it as a string when i view it. i have no idea why. Am i missing something super obvious?, any help would be appreciated.
Im also using node.js just to set up my local server, but i dont believe this is the problem.
var appdemo = angular.module('appdemo', []);
appdemo.controller('ctrl', function($scope) {
$scope.value1 = 1;
$scope.value2 = 2;
$scope.updateValue = function() {
$scope.x = $scope.value1 + ' x ' + $scope.value2 +
" = " (+$scope.value1 + +$scope.value2)
};
});
<!DOCTYPE html>
<html ng-app="appdemo">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>appdemo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div ng-controller="ctrl">
<span>times</span>
<input type="text" ng-model="value1" />
<input type="text" ng-model="value2" />
<button ng-click="updateValue()">total</button> {{x}} {{ value1 }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script src="main.js"></script>
</body>
</html>
this is my local server not entirely convinced if done it correctly.
const express = require('express')
const app = express()
app.use(express.static("public"))
app.engine("html", require("ejs").renderFile)
app.set("view engine", "html")
app.set("views", "./views")
app.get("/", (req, res) =>{
res.render("index")
})
app.listen(3000, ()=>{
console.log("Running on port 3000...")
})
file structure:
node_mdodules
public
css
views
index.html
main.js
app.js
package-lock.json
package.json
Let assume you have the next folder structure:
-App name
-public
-html
-index.html
-js
-main.js
-style.css
-server.js //Or any other name for your node js server
In your server js you should use the __dirname property:
app.use(express.static(__dirname + '/public'));
Then in your html replace your import script for this:
<script src="/js/main.js"></script>
I am serving a static html file using the app.use(express.static(__dirname+"views")). And when I go to localhost:3000/first.html I get the html file. But I don't know if the angularjs and other controller javascript files were executed. I think they were not executed because I use ng-model for a button's value and it's just an empty button with no text and the function is not executed for the ng-click.
I think maybe it's because only the html file is served by the server without my controller js and my downloaded angularjs which I have src'd to in the html. But I don't see a 404 or any error in the console.
And also, when I use a virtual path(like app.use(express.static('',__dirname+"/views"))), I don't get the html file when I go to localhost:3000/views/first.html.
This is my server.js:
(function(){
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));
// app.use(express.static('/views',__dirname+'/views')); this is not working
var server = http.createServer(app);
server.listen('3000');
console.log("Server is listening");
})();
My first.html which is served by the server:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title></title>
<base href="localhost:3000/">
</head>
<body>
<script type="text/javascript" src="./angular.js"></script>
<script type="text/javascript" src="./angular-route.js"></script>
<script type="text/javascript" src="./controller.js"></script>
<div ng-controller="firstController">
First name:<input type="text" ng-model="firstName"><br>
Last name:<input type="text" ng-model="lastName"><br>
<input type="button" ng-click="loadView()" ng-model="submit" name="">
</div>
</body>
</html>
This is the controller.js:
var app = angular.module('myapp', ['ngRoute']);
app.config(function($routeProvider,$locationProvider){
$routeProvider.when('/first',{
templateUrl:'/first.html',
controller: 'firstController'
})
.when('/second',{
templateUrl:'/second.html',
controller:'secondController'
})
.otherwise({
redirectTo:'/first'
})
$locationProvider.html5Mode(true);
})
console.log("controller");
app.controller('firstController',function($scope,$location){
$scope.firstName="";
$scope.lastName="";
$scope.loadView = function()
{
$location.path('views/second/'+$scope.firstName +"/" +$scope.lastName);
}
$scope.submit = "submit";
})
.controller('secondController',function($scope,$routeParams){
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})