I'm very much not a javascript person, but I've been making an Electron GUI, and I'm getting confused by why I can't seem to make a child browser window call its own js.
I have a main.js that does a bunch of things, setting up a tray menu, one option of which will spawn a browser window like this:
window = new BrowserWindow({
width: 360,
height: 320,
backgroundColor: "#D6D8DC",
show: false
})
window.setMenuBarVisibility(false);
window.loadURL(require('url').format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
And that window loads fine, and includes this reference to its own window.js, which is the way I've seen it done in Electron examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Radiam Agent</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<div id="container" class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Username</h3>
<input name="username" id="username" type="text" size="40"/>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Password</h3>
<input name="password" id="password" type="password" size="40"/>
</div>
</div>
<br/><br/>
<div class="button">
<button id="login">Get Radiam Login Token</button>
</div>
</div>
<script src="window.js" charset="utf-8"></script>
</body>
</html>
But the window.js code, which looks like this (the entire file), doesn't seem to fire ever:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login(event) {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("login").addEventListener("click", login(event));
})
Am I missing something? Again, not a js person (I'm building a GUI to a Python script, which is otherwise working great), but it seems like it should be obvious...
Thanks!
This worked. I think it was the wrong type of listener, plus I shouldn't have been trying to pass event:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.getElementById("login").addEventListener("click", login);
Related
My app works in live server but when i add nodejs, it doesn't work correctly. The Modal window does not pop up anymore and I do not know why. I have understood that I cant use localstorage or window properties because it is not on the browser anymore, but I cant figure out what to do instead of using those. Is there an npm package I can install to use localstorage and other browser side properties? Just looking for someone to point out my mistake and point me in the right direction. Any help is greatly appreciated. Thanks in advance!
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<script src="https://kit.fontawesome.com/4582c8b826.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<title>Issue Tracker</title>
</head>
<body>
<div class="contaienr">
<h1>Issue Tracker</h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueinputform">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select class="form-control" id="issueSeverity">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button id="add-issue" onclick="submitIssue()" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="emptyField" tabindex="-1" role="dialog" aria-labelledby="emptyFieldLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="emptyFieldLabel">Invalid Input!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Please provide the desciption of the issue and also the person name who you want to assign the issue.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
</body>
</html>
app.js
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
if ((description.length == 0) || (assignedTo.length == 0)) {
alert("Please fill all fields with required data.");
document.getElementById('add-issue').setAttribute("data-toggle", "modal");
document.getElementById('add-issue').setAttribute("data-target", "#emptyField")
}
else {
document.getElementById('add-issue').removeAttribute("data-toggle", "modal");
document.getElementById('add-issue').removeAttribute("data-target", "#emptyField")
const issue = { id, description, severity, assignedTo, status };
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
currentIssue.description = `<strike>${currentIssue.description}</strike>`
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => ((issue.id) != id))
localStorage.removeItem('issues');
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (let i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3> ${description} </h3>
<p><i class="fa-solid fa-bolt"></i> ${severity}</p>
<p><i class="fa-solid fa-user"></i> ${assignedTo}</p>
<button onclick="closeIssue(${id})" class="btn btn-warning">Close</button>
<button onclick="deleteIssue(${id})" class="btn btn-danger">Delete</button>
</div>`;
}
}
fetchIssues();
main.js(server)
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const ejs = require('ejs')
const app = express();
const path = require('path');
const morgan = require('morgan')
const bcrypt = require('bcrypt');
const saltRounds = 10;
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('tiny'))
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});
const userSchema = new mongoose.Schema ({
email: String,
password: String
});
const User = new mongoose.model("User", userSchema)
app.get('/', function(req,res){
// res.sendFile(path.join(__dirname, '/index.html'));
res.redirect('/login')
});
app.get('/login', function (req,res){
// res.sendFile(path.join(__dirname, '/login/login.html'));
res.render('login')
})
app.get('/register', function(req,res){
res.render("register")
});
app.post('/register', function(req,res){
bcrypt.hash(req.body.password, saltRounds, function(err,hash) {
const newUser = new User({
email: req.body.username,
password: hash
});
newUser.save(function(err){
if(err){
console.log(err)
} else{
res.sendFile(path.join(__dirname+'/home.html'));
}
});
});
});
app.get('/home', function(req,res){
res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue()
})
// app.get('/home?', function(req,res){
// // res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue();
// })
app.post('/login', function(req,res){
const username = req.body.username;
const password = req.body.password;
User.findOne({email: username}, function(err,foundUser){
if(err){
console.log(err)
} else{
if(foundUser){
bcrypt.compare(password, foundUser.password, function(err, result) {
// res.sendFile(path.join(__dirname+'/home.html'));
res.redirect('/home')
});
}
}
})
})
app.listen(5000,function(){
console.log("server runnin on 5000")
})
I'm trying to run this example in the browser
https://justadudewhohacks.github.io/face-api.js/docs/index.html#getting-started-browser
Specifically this code here
<!DOCTYPE html>
<html>
<head>
<script src="assets/face-api.js"></script>
<script src="assets/commons.js"></script>
<script src="assets/faceDetectionControls.js"></script>
<link rel="stylesheet" href="assets/styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</head>
<body>
<div id="navbar"></div>
<div class="center-content page-container">
<div class="progress" id="loader">
<div class="indeterminate"></div>
</div>
<div style="position: relative" class="margin">
<video onloadedmetadata="onPlay(this)" id="inputVideo" autoplay muted playsinline></video>
<canvas id="overlay" />
</div>
<div class="row side-by-side">
<!-- face_detector_selection_control -->
<div id="face_detector_selection_control" class="row input-field" style="margin-right: 20px;">
<select id="selectFaceDetector">
<option value="ssd_mobilenetv1">SSD Mobilenet V1</option>
<option value="tiny_face_detector">Tiny Face Detector</option>
</select>
<label>Select Face Detector</label>
</div>
<!-- face_detector_selection_control -->
<!-- check boxes -->
<div class="row" style="width: 220px;">
<input type="checkbox" id="hideBoundingBoxesCheckbox" onchange="onChangeHideBoundingBoxes(event)" />
<label for="hideBoundingBoxesCheckbox">Hide Bounding Boxes</label>
</div>
<!-- check boxes -->
<!-- fps_meter -->
<div id="fps_meter" class="row side-by-side">
<div>
<label for="time">Time:</label>
<input disabled value="-" id="time" type="text" class="bold">
<label for="fps">Estimated Fps:</label>
<input disabled value="-" id="fps" type="text" class="bold">
</div>
</div>
<!-- fps_meter -->
</div>
<!-- ssd_mobilenetv1_controls -->
<span id="ssd_mobilenetv1_controls">
<div class="row side-by-side">
<div class="row">
<label for="minConfidence">Min Confidence:</label>
<input disabled value="0.5" id="minConfidence" type="text" class="bold">
</div>
<button
class="waves-effect waves-light btn"
onclick="onDecreaseMinConfidence()"
>
<i class="material-icons left">-</i>
</button>
<button
class="waves-effect waves-light btn"
onclick="onIncreaseMinConfidence()"
>
<i class="material-icons left">+</i>
</button>
</div>
</span>
<!-- ssd_mobilenetv1_controls -->
<!-- tiny_face_detector_controls -->
<span id="tiny_face_detector_controls">
<div class="row side-by-side">
<div class="row input-field" style="margin-right: 20px;">
<select id="inputSize">
<option value="" disabled selected>Input Size:</option>
<option value="128">128 x 128</option>
<option value="160">160 x 160</option>
<option value="224">224 x 224</option>
<option value="320">320 x 320</option>
<option value="416">416 x 416</option>
<option value="512">512 x 512</option>
<option value="608">608 x 608</option>
</select>
<label>Input Size</label>
</div>
<div class="row">
<label for="scoreThreshold">Score Threshold:</label>
<input disabled value="0.5" id="scoreThreshold" type="text" class="bold">
</div>
<button
class="waves-effect waves-light btn"
onclick="onDecreaseScoreThreshold()"
>
<i class="material-icons left">-</i>
</button>
<button
class="waves-effect waves-light btn"
onclick="onIncreaseScoreThreshold()"
>
<i class="material-icons left">+</i>
</button>
</div>
</span>
<!-- tiny_face_detector_controls -->
</body>
<script>
let forwardTimes = []
let withBoxes = true
function onChangeHideBoundingBoxes(e) {
withBoxes = !$(e.target).prop('checked')
}
function updateTimeStats(timeInMs) {
forwardTimes = [timeInMs].concat(forwardTimes).slice(0, 30)
const avgTimeInMs = forwardTimes.reduce((total, t) => total + t) / forwardTimes.length
$('#time').val(`${Math.round(avgTimeInMs)} ms`)
$('#fps').val(`${faceapi.utils.round(1000 / avgTimeInMs)}`)
}
async function onPlay() {
const videoEl = $('#inputVideo').get(0)
if(videoEl.paused || videoEl.ended || !isFaceDetectionModelLoaded())
return setTimeout(() => onPlay())
const options = getFaceDetectorOptions()
const ts = Date.now()
const result = await faceapi.detectSingleFace(videoEl, options).withFaceExpressions()
updateTimeStats(Date.now() - ts)
if (result) {
const canvas = $('#overlay').get(0)
const dims = faceapi.matchDimensions(canvas, videoEl, true)
const resizedResult = faceapi.resizeResults(result, dims)
const minConfidence = 0.05
if (withBoxes) {
faceapi.draw.drawDetections(canvas, resizedResult)
}
faceapi.draw.drawFaceExpressions(canvas, resizedResult, minConfidence)
}
setTimeout(() => onPlay())
}
async function run() {
// load face detection and face expression recognition models
await changeFaceDetector(TINY_FACE_DETECTOR)
await faceapi.loadFaceExpressionModel('/')
changeInputSize(224)
// try to access users webcam and stream the images
// to the video element
const stream = await navigator.mediaDevices.getUserMedia({ video: {} })
const videoEl = $('#inputVideo').get(0)
videoEl.srcObject = stream
}
function updateResults() {}
$(document).ready(function() {
renderNavBar('#navbar', 'webcam_face_expression_recognition')
initFaceDetectionControls()
run()
})
</script>
</body>
</html>
Unfortunately this is not working ( I have loaded the associated libraries into assets, i.e., https://github.com/justadudewhohacks/face-api.js/tree/master/dist and moving the other files from this example here
https://github.com/justadudewhohacks/face-api.js/tree/master/examples/examples-browser
What am i doing wrong? I am loading this on a page on my site here
https://moodmap.app/webcamFaceExpressionRecognition.html in case you want to see what's happening in the browser.
Based on changes below,
Here is the node server where I am setting where things are held - is it possible to just change this instead? As it is coming up with a separate issue with the shard needed in the model as well now when making the changes suggested below.
Thanks!
const config = require('../../config');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, { wsEngine: 'ws' });
const mysql = require('mysql');
const expressSession = require('express-session');
const ExpressMysqlSessionStore = require('express-mysql-session')(expressSession);
const sharedsession = require('express-socket.io-session');
const path = require('path');
const utils = require('./utils');
// remove from header "X-Powered-By: Express"
app.disable('x-powered-by');
server.listen(config.serverParams.port, config.serverParams.address, () => {
console.log(`Server running at http://${server.address().address}:${server.address().port}`);
});
/* DATABASE */
global.db = mysql.createConnection(config.db);
db.connect();
/* DATABASE */
/* SESSION */
const sessionStore = new ExpressMysqlSessionStore(config.sessionStore, db);
const session = expressSession({
...config.session,
store: sessionStore,
});
app.use(session);
/* SESSION */
app.use(express.static(config.frontendDir));
app.use(express.static(path.join(__dirname, './src/assets')))
app.use(express.static(path.join(__dirname, './src/assets/weights')))
app.use((req,res,next)=>{
//can reaplce * with website we want to allow access
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get([
'/signup',
'/stats',
'/pay',
], (req, res) => res.sendFile(path.join(`${config.frontendDir}${req.path}.html`)));
io.use(sharedsession(session, {
autoSave: true
}));
io.on('connection', socket => {
socket.use((packet, next) => {
if (packet[0]) {
console.log('METHOD:', packet[0]);
const sessionData = socket.handshake.session.user;
const noSessionNeed = [ 'login', 'signup', 'checkAuth' ].includes(packet[0]);
let error;
if ( ! sessionData && ! noSessionNeed) error = { code: -1, message: 'You need to login in extension!' };
if (error) return next(new Error(JSON.stringify(error)));
else next();
}
});
const auth = require('./auth')(socket);
socket.on('checkAuth', auth.checkAuth);
socket.on('login', auth.login);
socket.on('signup', auth.signup);
socket.on('logout', auth.logout);
const users = require('./users')(socket);
socket.on('users.get', users.get);
const sentiment = require('./sentiment')(socket);
socket.on('sentiment.get', sentiment.get);
socket.on('sentiment.set', sentiment.set);
socket.on('disconnect', () => {
});
});
Reason being still getting an error for some reason as below,?
fetchOrThrow.ts:11 Uncaught (in promise) Error: failed to fetch: (404) , from url: https://moodmap.app/assets/tiny_face_detector_model-weights_manifest.json
at fetchOrThrow.ts:11
at step (drawContour.ts:28)
at Object.next (drawContour.ts:28)
at fulfilled (drawContour.ts:28)
(anonymous) # fetchOrThrow.ts:11
step # drawContour.ts:28
(anonymous) # drawContour.ts:28
fulfilled # drawContour.ts:28
async function (async)
run # webcamFaceExpressionRecognition.html:142
(anonymous) # webcamFaceExpressionRecognition.html:158
j # jquery-2.1.1.min.js:2
fireWith # jquery-2.1.1.min.js:2
ready # jquery-2.1.1.min.js:2
I # jquery-2.1.1.min.js:2
Thanks in advance!
So, the error you were talking about in the question is:
Uncaught (in promise) Error: failed to fetch: (404) , from URL:
https://moodmap.app/tiny_face_detector_model-weights_manifest.json
So, this error implies that the file tiny_face_detector_model-weights_manifest.json could not be found. And this is happening for all other manifest.json files as well, as I see in your website.
You mentioned in the question that all your associated libraries are into assets folder. So, your tiny_face_detector_model-weights_manifest.json file and other manifest.json files also in assets folder and I am giving you the solution according to that but if you change location of files to another folder, just replace assets with that whatever folder where your file is in.
face-api.js Line:1976
Here, in line 1976 you see defaultModelName. This tells about the file to load.
1. So if your app has only the issue with loading tiny_face_detector_model-weights_manifest.json [ For this case, It is showing 404 error for all manifest.json so jump below] then
face-api.js Line: 5627
Go to line 5627 in face-api.js and change
"tiny_face_detector_model" with
"./assets/tiny_face_detector_model"
2. If all your manifest files are showing 404 error while loading, which true for this case because all your files are in assets folder.
So, in that case go to line number 1976 of face-api.js,
just replace:
var defaultManifestFilename=defaultModelName+"-weights_manifest.json";
with:
var defaultManifestFilename="./assets/"+defaultModelName+"-weights_manifest.json";
That means just concatenate the folder name or path where the manifest file exists to the mentioned variable. And this will fix the path issue for all manifest.json files in your application.
NOTE: If there is a problem finding the code with line number I mentioned then use search.
There is a simple express.js app , which has to connect to the mysql database and then gets the information from the user for registering in database . although the app connects to the database correctly , but no action has been performed on the register button click . Here is my code
App.js
var express = require("express");
var login = require('./routes/register');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname + "/static"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var path = require('path');
//app.set('views', path.join(__dirname, 'static/views'));
//app.use('/scripts', express.static(path.join(__dirname, 'node_modules')));
//app.use(express.static(path.join(__dirname, 'static')));
var engines = require('consolidate');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
var router = express.Router();
app.get('/',function (req,res) {
res.sendFile(__dirname + '/static/register.html');
});
router.post('/register',register.register);
app.use('/api', router);
app.listen(5000);
register.js
var express = require("express");
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'CREBA'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
exports.register = function(req,res){
// console.log("req",req.body);
var USER={
"NAME":req.body.firstname,
"FAMILY":req.body.lastname,
"ID":req.body.personaly,
"POS":req.body.position
}
connection.query('INSERT INTO USER SET ?',USER, function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
console.log({
"code":400,
"failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
console.log({
"code":200,
"success":"user registered sucessfully"
});
}
});
}
HTML :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Node Js APP</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/home.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/home.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<h1 id="header">Node JS APP</h1><span id="auth" class="label label-info"> -- </span>
<div id="authBox">
<div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%">
<h3> Login </h3>
<div> <span>first</span><input class="form-control" id="firstname"> </div>
<div> <span>last</span> <input class="form-control" id="lastname"> </div>
<div> <span>last</span> <input class="form-control" id="personaly"> </div>
<div> <span>last</span> <input class="form-control" id="position"> </div>
<button style="margin: 5px" class="btn btn-primary" id="register"> register </button>
</div>
<div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%" >
<h3> Sign Up </h3>
<div><span> Username</span><input class="form-control" id="signUpUser"> </div>
<div><span> Password </span> <input class="form-control" id="signUpPass"> </div>
<button style="margin: 5px" class="btn btn-primary" id="signUp"> Sign Up !</button>
</div>
</div>
</div>
</div>
<div class="alert alert-danger" style="text-align: center ; "></div>
<div class="alert alert-success" style="text-align: center ;"></div>
<div style="text-align: center ; border: 1px solid #e2e2e2 ; margin: 20px " id="cmBox">
<div style="width:75% ; padding: 20px ; margin: auto "><span> Enetr Comment: </span> <input class="form-control" id="msg"> </div>
<button class="btn btn-success" id="submitComment"> Submit </button>
<ul id="commentBox" class="list-group" style="margin: 25px 20%">
</ul>
</div>
home.js
$(document).ready(function () {
var isAuth = false ;
var errorBox = $("div.alert-danger") ;
var successBox = $("div.alert-success") ;
successBox.slideUp(1);
errorBox.slideUp(1);
console.log(successBox);
$("#register").click(function () {
console.log({ firstname : $("#firstname").val() ,lastname : $("#lastname").val() , personaly : $("#personaly").val() ,POS : $("#POS").val() }) ;
$.post("/register" , { username : $("#firstname").val() ,password : $("#lastname").val ,( "#personaly").val() ,POS : $("#POS").val() } , function (data) {
if (data['status']) {
successBox.slideUp(1);
errorBox.slideUp(1);
successBox.html(data['msg']).slideDown(500) ;
getInfo() ;
}
else {
successBox.slideUp(1);
errorBox.slideUp(1);
errorBox.html(data['msg']).slideDown(500) ;
getInfo() ;
}
})
}) ;
getInfo() ;
}) ;
I suspect you have a 404 Not found ;) (not sure though, but from what I can see).
These lines in your express app:
router.post('/register',register.register);
app.use('/api', router);
I haven't work with express for a while, but from my recollection, it means that in your client application, you should call /api/register and not /register.
Try this: $.post("/api/register" ... in your home.js file.
Moreover, watchout:
Your post handler in the express server reads the position parameter this way:
req.body.position
but the client sends it in POS, not position, so, the position value will likely always be undefined in your server.
I just started using oidc-client-js, so i am really confused trying to understand it . I have the below question :) .
I have been connected to a remote webserver running OpenIDConnect and specifically using https://github.com/mitreid-connect/OpenID-Connect-Java-Spring-Server i have builded the openid-connect-server-webapp and created a client correctly. It is hosted on a vm .
I followed this tutorial -> link
Link of 3 html files i modified for the tutorial i followed ->
here
The error that is shown on the console:
All good as you can see on the image below , i authorized the simple javascript app and i am getting back the access_token along with id_token , though when i am trying to call the API , boom i get error and i don't know why ?
The html index code i have is ( in case it helps you ) :
<!DOCTYPE html>
<html>
<head>
<title>JS Application</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" />
<style>
.main-container {
padding-top: 70px;
}
pre:empty {
display: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">JS Application</a>
</div>
</div>
</nav>
<div class="container main-container">
<div class="row">
<div class="col-xs-12">
<ul class="list-inline list-unstyled requests">
<li>Home</li>
<li><button type="button" class="btn btn-default js-login">Login</button></li>
<li><button type="button" class="btn btn-default js-call-api">Call API</button></li>
<li><button type="button" class="btn btn-danger js-logout">Logout</button></li>
</ul>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">User data</div>
<div class="panel-body">
<pre class="js-user"></pre>
</div>
</div>
</div>
<div class="col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">API call result</div>
<div class="panel-body">
<pre class="js-api-result"></pre>
</div>
</div>
</div>
</div>
</div>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
<script src="node_modules/oidc-client/dist/oidc-client.js"></script>
<script>
// helper function to show data to the user
function display(selector, data) {
if (data && typeof data === 'string') {
data = JSON.parse(data);
}
if (data) {
data = JSON.stringify(data, null, 2);
}
$(selector).text(data);
}
var settings = {
authority: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp',
client_id: 'client',
client_secret: "secret",
user_id: "user",
popup_redirect_uri: 'http://localhost/jsApp/popup.html',
silent_redirect_uri: 'http://localhost/jsApp/silent-renew.html',
post_logout_redirect_uri: 'http://localhost/jsApp/index.html',
response_type: 'token id_token',
scope: 'openid profile email offline_access',
filterProtocolClaims: false
};
var manager = new Oidc.UserManager(settings);
var user;
Oidc.Log.logger = console;
manager.events.addUserLoaded(function (loadedUser) {
user = loadedUser;
display('.js-user', user);
});
manager.events.addSilentRenewError(function (error) {
console.error('error while renewing the access token', error);
});
manager.events.addUserSignedOut(function () {
alert('The user has signed out');
});
$('.js-login').on('click', function () {
manager
.signinPopup()
.catch(function (error) {
console.error('error while logging in through the popup', error);
});
});
$('.js-call-api').on('click', function () {
var headers = {};
if (user && user.access_token) {
headers['Authorization'] = 'Bearer ' + user.access_token;
}
$.ajax({
url: 'http://snf-761523.vm.okeanos.grnet.gr:8080/openid-connect-server-webapp/api/tokens/access',
method: 'GET',
dataType: 'json',
headers: headers
}).then(function (data) {
display('.js-api-result', data);
}).catch(function (error) {
display('.js-api-result', {
status: error.status,
statusText: error.statusText,
response: error.responseJSON
});
});
});
$('.js-logout').on('click', function () {
manager
.signoutRedirect()
.catch(function (error) {
console.error('error while signing out user', error);
});
});
</script>
</body>
</html>
There is a temporary solution tough only for testing your application and not for production , disabling Web-Security on Google Chrome
FIRST YOU NEED TO KILL ALL THE INSTANCES OF CHROME , then install a Plugin Called CORS Toggle
and finally run the bellow commants from Terminal or Commant Prompt
For Windows
.\chrome --args --disable-web-security --user-data-dir
For Ubuntu Linux (tested only there)
/opt/google/chrome/google-chrome --args --disable-web-security --user-data-dir
I am developing basic application that has a simple membership. Besides, i need to develop Sessions aswell. In my following code, sockets do not respond. Can you help me to find the reason behind that ?
app.js
var WebApp = require('./webApp.js');
var db = require('./db/db.js');
var db = new db();
var webApp = new WebApp();
var App = function(){}
webApp.initialize();
webApp.socketIOConnect(function(client){
webApp.socketIOConnectMethods(client);
});
module.exports = App;
webApp.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var socketHandshake = require('socket.io-handshake');
var io = require('socket.io')(server);
io.use(socketHandshake({secret:'secret',resave : false, saveUninitialized : true, parser:cookieParser()}));
server.listen(1185);
var WebApp = function () {
console.log("Greetings from WebApp Module.");
}
var db = new Db();
WebApp.prototype.initialize = function () {
app.use(express.static("./assets"));
router.get('/', function (req, res, next) {
res.sendFile("./assets/index.html");
});
router.get('/login', function (req, res, next) {
res.sendFile(path.resolve("./assets/login.html"));
});
router.get('/client', function (req, res, next) {
res.sendFile(path.resolve("./client/client.html"));
});
app.use(router);
}
WebApp.prototype.socketIOConnect = function(callback) {
io.on('connection', function(client, req, res) {
callback(client)
});
}
WebApp.prototype.socketIOConnectMethods = function (client) {
if (client.handshake.session.name) {
console.log('We already know you!');
client.emit('get name');
client.emit('redirect');
};
client.on('join', function(data) {
console.log(data);
});
client.on('register', function(data) {
client.emit('username', data);
console.log(data);
var checkAuth;
var username = data.user;
var password = data.passw;
var email = data.email;
var confpass = data.confirmPass;
console.log("password : "+password);
console.log("conf password :"+confpass);
if ( password == confpass){
console.log("Passwords match, this lad can login");
var values = [[, username, password, email]];
console.log(username + " " + password + " " + email);
db.registAuth(email,function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
client.on('passwordmatches',function(data){
console.log(data);
});
console.log(results);
var checkAuth = results.length;
if(results < 1){
db.userRegistration(values,function(err, results) {
if(err) {
console.log("An error occurred: " + err.message);
}
console.log(results);
});//user registration
}
else{console.log("Sorry, we could not complete your registration. Email already exists.");}
});//registAuth
}
else{
client.on('NoMatchPass',function(data){
console.log(data);
});
console.log("Sorry, we could not complete your registration. Passwords do not match !");
client.emit('tryagainreg',"Sorry, we could not complete your registration. Passwords do not match !");
}
});//client.on register
client.on('login', function(data) {
var email = data.email;
var password = data.password;
console.log(data);
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
client.handhsake.session.name = email;
client.handshake.session.save();
console.log(client.handshake.session.name);
client.emit('AuthLogin',email);
}
else{console.log("Wrong username or password.");
client.emit('FailedLogin',email);
}
});
});
};
module.exports = WebApp;
I want user to login when they completed their registration successfully and then, when they logged in successfully i want to redirect them client.html but with session so that i can keep them authorized till they logged out of the applicaton.
login.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Let's Get Head In</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<!-- Fonts and icons -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<!-- CSS Files -->
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<link href="./css/material-kit.css" rel="stylesheet"/>
</head>
<body class="signup-page">
<nav class="navbar navbar-transparent navbar-absolute">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-example">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="">AslanServices</a>
</div>
<div class="collapse navbar-collapse" id="navigation-example">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="./index.html" target="">
Register
</a>
</li>
<li>
<a href="" target="">
<i class="material-icons">unarchive</i>Contact
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="wrapper">
<div class="header header-filter" style="background-image: url('./img/city.jpg'); background-size: cover; background-position: top center;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
<div class="card card-signup">
<form class="loginform" method="" action="">
<div class="header header-primary text-center">
<h4>Sign In</h4>
</div>
<div class="content">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<input type="text" class="form-control" id="email" placeholder="Email...">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<input type="password" placeholder="Password..." id="password" class="form-control" />
</div>
<!-- If you want to add a checkbox to this form, uncomment this code
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked>
Subscribe to newsletter
</label>
</div> -->
</div>
<div class="footer text-center">
<button type="submit" class="btn" value="Submit">Sign in!</button>
</div>
</form>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<nav class="pull-left">
<ul>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
AslanServices
</a>
</li>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
About Us
</a>
</li>
</ul>
</nav>
<div class="copyright pull-right">
© 2017, made by Aslanmeister
</div>
</div>
</footer>
</div>
</div>
</body>
<!-- Core JS Files -->
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
<script src="./js/material.min.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="./js/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the Datepicker, full documentation here: http://www.eyecon.ro/bootstrap-datepicker/ -->
<script src="./js/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Control Center for Material Kit: activating the ripples, parallax effects, scripts from the example pages etc -->
<script src="./js/material-kit.js" type="text/javascript"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('127.0.0.1:1185');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
socket.on('redirect',function(callback){ callback(window.location.href="127.0.0.1:1185/client");
});
$('form.loginform').submit(function(event){
event.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
socket.emit('login',{email : email, password : password});
socket.on('AuthLogin',function(data){window.location.href = 127.0.0.1:1185/client";});
socket.on('FailedLogin',function(data){alert('Wrong username or Password. Maybe, you dont even exist!');window.location.href = "127.0.0.1:1185";});
});
});
</script>
</html>
I simply solved my problem by using this code below.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(cookieParser('aslan'));
var redis = require("redis");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var io = require('socket.io')(server);
var cookie = require('cookie');
//var passwordHash = require('password-hash');
var redisclient = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true }));
var sessionMiddleware = session({
store: new RedisStore({host : 'localhost' , port : '6379' , client : redisclient , ttl : 15}), // redis server config
secret: 'aslan',
resave : false,
saveUninitialized : false
});
app.use(sessionMiddleware);
//---------------CONFIG PART ENDED-------------
app.get('/',function (req, res, next) {
session = req.session;
if ( session.key ){
res.redirect('/'+session.key+'');
}
res.sendFile("./assets/index.html");
});
//---------------------------------
app.get('/login', function (req,res,next) {
session = req.session;
if ( session.key ){
if ( session.key == 'admin#gmail.com'){res.redirect('/admin');}
if ( session.key != 'admin#gmail.com'){res.redirect('/'+session.key);}
}
res.sendFile(path.resolve("./assets/login.html"));
});
//--------------------------------LOGIN POST------------------
app.post('/login', function (req,res,next) {
console.log("hi from login post");
var email = req.body.user.email;
var password = req.body.user.password;
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
//session
session = req.session;
session.key = email;
db.returnUsername(session.key,function(err,result){
if (err) {
console.log('An Error Occured in Db :' + err.message);
}
console.log(result);
console.log(session.key+'Before checking');
if ( session.key == 'admin#gmail.com'){console.log('Session key is equal to admin#gmail.com'); res.redirect('/admin');}
if ( session.key != 'admin#gmail.com'){console.log('Session key is not equal to admin#gmail.com'); res.redirect('/evsahibi');}
});
}
else{console.log("Wrong username or password.");}
});
});