not able to do routing properly in page.js - javascript

I am using page.js for routing in a Single Page Application. For testing purpose, I am using npm http-server.
I am not able to do routing. I am not sure what I am missing. following is my code:
index.html:
<html>
<head>
<title>test page!</title>
<script src="/js/libs/page.js"></script>
</head>
<body>
this is body of test
Simple test
<script type="text/javascript" src="/js/routes.js"></script>
</body>
</html>
routes.js
function initRoutes () {
var testRoutes = {
test : function (context, next) {
alert("testing");
if(next){
next();
}
},
test2 : function (context, next) {
alert("I am jon snow, I know nothing.");
}
};
page.base('/');
page('/', testRoutes.test);
page('/test', testRoutes.test2);
page('/two-args', testRoutes.test, testRoutes.test2);
page();
}
initRoutes();
from my http-server, I am accessing http://0.0.0.0:8081. I am getting an test as alert, but I am not getting the alert for route http://0.0.0.0:8081/test.
I am not sure what I am missing. Please let me know if you need anything else.

Related

How can i use script src?

I am trying to use errLogin module in js code in html file.
THis is main.js file.
import puppeteer from "puppeteer"
const errLogin = false;
...
export default { errLogin }
THis is test.html file.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>main</title>
<style>
body {
font-family: Consolas, monospace;
}
</style>
<script src="./account.js"></script>
<script type="module">
import { errLogin } from "./main.js"
console.log(errLogin)
</script>
</head>
<body>
<div>
<p id="email"></p>
<p id="password"></p>
</div>
<script>
const CirculateData = () =>{
for (let key in account)
{
if (!errLogin) return account[key];
else return account[Number(key) + 1];
}
};
document.querySelector("#email").innerHTML = CirculateData().email
document.querySelector("#password").innerHTML = CirculateData().password
</script>
</body>
</html>
error message.
Uncaught TypeError: Failed to resolve module specifier "puppeteer". Relative references must start with either "/", "./", or "../".
this is folder structure.
How can I do it? How can I do it? How can I do it?How can I do it? How can I do it? How can I do it? How can I do it? How can I do it? How can I do it? How can I do it?
Type module work with src argument, then browsers don't know about import|export, you need Webpack or another bundler

How to update html document using feather js?

I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>

Firefox Storage Access API denies local storage after successful requestStorageAccess() call

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.

Routers apparently doing nothing locally in Backbone.js

I recently was fiddling with Backbone.js and I got everything to work (Models/Views/Events/Collections) except the Router. Here is my js/router/test.js file.
var Router = Backbone.Router.extend({
routes: {
'' : 'index',
'projects/:id' : 'show'
},
start: function() {
Backbone.history.start({ pushState : true });
},
index: function() {
alert('index');
},
show: function(id) {
alert(id);
}
});
var router = new Router();
router.start();
And here is my test.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<title> sup </title>
</head>
<body>
<p> hello </p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- jQuery -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"> </script> <!-- underscore.js -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"> </script> <!-- backbone.js -->
<script src="js/routers/test.js"></script>
</body>
</html>
If I put an alert('Hi!') in initialize: within my Router the alert pop ups correctly. I am navigating to file:///Users/myname/Projects/backbone/test.html as the base page. Should I be setting a urlRoot somewhere? Any help is appreciated.
The problem was that Backbone.js acts differently using file:/// URLs and needs to have a webserver serving the files.
The solution was to move my files into my ~/Sites folder and configure and start Apache. I followed the guide here: http://www.coolestguidesontheplanet.com/downtown/get-apache-mysql-php-and-phpmyadmin-working-osx-109-mavericks.

Knockout JS: ko.applyBindings is not a function

I'm trying to use Knockout js in a simple web application.
Here's my dummy javascript code:
function MainViewModel() {
this.myText = ko.observable('Hello world');
}
var MainViewModelInstance = new MainViewModel();
ko.applyBindings(MainViewModelInstance);
But when I run the index.html, the debug console says "ko.applyBindings is not a function"!
Help!
Thanks
You have not included the link to the knockout.js library in your source code or the link is wrong. Fix this and it will work.
<script src="/scripts/knockout-2.0.0.js" type="text/javascript"></script>
Where the /scripts directory is the location on the server where knockoutjs resides.
EDIT
Here is an example of your code that works.
<html>
<head>
<script src="knockout-2.0.0.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function MainViewModel() {
this.myText = ko.observable('Hello world');
}
var MainViewModelInstance = new MainViewModel();
ko.applyBindings(MainViewModelInstance);
</script>
</body>
</html>

Categories

Resources