I am trying to encrypt some text for a HTML project that I am doing and the encryption code I'm using requires a node.js server, but I can't seem to run the function in my original HTML code. I am new to JavaScript and don't really understand a lot of it.
This is the HTML code where I want to call the function with the button:
(the stuff in the button is just some random thing from online and I don't think is relevant)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>test</title>
</head>
<body>
<a href="/Files/TEST.ptf" download="meme14">
TEST.ptf
</a>
<button onclick="
var url = require('url');
var adr = 'http://localhost:3000';
var q = url.parse(adr, true);
console.log(q.host);"
>Encrypt</button>
</body>
</html>
Here is the Node.JS Server's code, I want to call the encrypt function.
// server.js
var express = require('express');
var app = express();
var PORT = 3000;
app.get('/', function(req, res) {
res.status(200).send('Hello world');
});
function encrypt() {
var SimpleCrypto = require("simple-crypto-js").default;
var _secretKey = "-VH5s*#yoj0JDiXQdLyKHwYvttDeoxcarpgaBm9uLZH%Vy0Xw_n0DZ3|BgE7pn%1*APiRV1L*7OlRLIuL&yqIqKw#QLPJc+r+N^dH-Wb3#Zx2TKkvtbobzFW6?Fr$^XObG4K$m$clU3m+1BVx#3O_v6sikvNWwxhVV*q4vrvr7|8qT4*JK3g!*SF-ffDE=?lU$4HuVpiYHTAmW#DNDWeJH*#orX_GY##|=8ip8rskE0TPl-4OC+KCa2re+ND3pwp";
var simpleCrypto1 = new SimpleCrypto(_secretKey);
var plainText = "Hello World!";
var cipherText = simpleCrypto1.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text : " + plainText);
console.log("Cipher Text : " + cipherText);
}
var router = express.Router();
app.use('/*', router);
router.get('/call-java-app', function (req, res, next){
encrypt();
res.send(cipherText);
});
encrypt();
app.listen(PORT, function() {
console.log('Server is running on PORT:',PORT);
});
In your NodeJS code you have to create a Route that call this function and send to client the response; technically.
I hope this code can help you:
var express = require('express');
var app = express();
var PORT = 3000;
var SimpleCrypto = require("simple-crypto-js").default;
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.get('/', function (req, res) {
res.status(200).send('Hello world');
});
app.get('/encrypt', function (req, res) {
res.send(encrypt())
});
app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
});
function encrypt() {
var _secretKey = "-VH5s*#yoj0JDiXQdLyKHwYvttDeoxcarpgaBm9uLZH%Vy0Xw_n0DZ3|BgE7pn%1*APiRV1L*7OlRLIuL&yqIqKw#QLPJc+r+N^dH-Wb3#Zx2TKkvtbobzFW6?Fr$^XObG4K$m$clU3m+1BVx#3O_v6sikvNWwxhVV*q4vrvr7|8qT4*JK3g!*SF-ffDE=?lU$4HuVpiYHTAmW#DNDWeJH*#orX_GY##|=8ip8rskE0TPl-4OC+KCa2re+ND3pwp";
var simpleCrypto1 = new SimpleCrypto(_secretKey);
var plainText = "Hello World!";
var cipherText = simpleCrypto1.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text : " + plainText);
console.log("Cipher Text : " + cipherText);
}
you have to use Ajax to send a request to server and get the response and show to the user, make an Ajax request can help you.
Related
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('proiect'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage.html');
else
res.redirect('login-error.html');
res.end();
});
app.get('/homepage.html',function(req,res){
console.log('aaa');
});
app.get('bios.html',function(req,res){
console.log('aaa');
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage.html');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login.html');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
The server doesnt handle the app.get('homepage.html') or 'bios.html' it just displays the html file in the browser.(should hang and display smth on console).
Am i supposed to serve/render those files instead of directly accessing them in the browser?
Both of those files are in the /proiect/ folder i've included on the server.
Express finds the static HTML file and then returns that to the user. Therefore it skips the route handler you wrote.
If you are trying to perform some server-side logic and returning an HTML page, rather return the page inside your route handler to avoid such side effects. In this case, create your HTML file in a templates folder or something. Then you can put all your static resources in your static folder. So your structure would look something like this:
+ project_folder
+ static
+ css
- style.css
+ js
- app.js
+ templates
- bios.html
- homepage.html
- login.html
- login-error.html
- app.js
Then your app.js would look something like this:
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('static'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.get('/login', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login.html'));
});
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage');
else
res.redirect('login-error');
res.end();
});
app.get('/homepage',function(req,res){
res.sendFile(path.join(__dirname, '/templates/homepage.html'));
});
app.get('bios',function(req,res){
res.sendFile(path.join(__dirname, '/templates/bios.html'));
});
app.get('login-error', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login-error.html'));
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
I have a node.js/socket.io project. I'm using Bootstrap in my pages and I display images dynamically on my pages. The problem is that I can't use the images and the Bootstrap files. Node.js/socket.io doesn't recognize the links... I have solved the Bootstrap problem by uploading all Bootstrap files on a distant server and it works! But I can't use local files like my images.
How can I "load" an image folder which I can use the images from it?
Here is my server.js :
var http = require('http').createServer(createServer);
var fs = require('fs');
var url = require('url');
var nStatic = require('node-static');
var express = require('express');
var app = express();
function createServer(req, res) {
var path = url.parse(req.url).pathname;
var fsCallback = function(error, data) {
if(error) throw error;
res.writeHead(200);
res.write(data);
res.end();
}
switch(path) {
case '/galerie.php':
doc = fs.readFile(__dirname + '/galerie.php', fsCallback);
break;
default:
doc = fs.readFile(__dirname + '/index.php', fsCallback);
break;
}
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
http.listen(8080);
This works :
<script src="http://website.ch/LivreOr/js/download.js"></script>
But this doesn't work :
<img src="../LivreOr/img/img.png">
I have solved my problem. Here is what I have changed :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/galerie', function(req, res) {
res.sendFile(__dirname + '/galerie.html');
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
//var io = require('socket.io').listen(http);
io.sockets.on('connection', function (socket, pseudo) {
...
});
server.listen(8080);
I am able to run my node.js server, my phaser.js game runs but I get no 'connected' console.log when the game runs. I instead get this error message from the client end:
enter image description here
socket.io-1.4.5.js:1 GET http://192.168.128.184:8080/socket.io/?EIO=3&transport=polling&t=LdMR6Ro net::ERR_CONNECTION_REFUSED
SERVER:
var serverPort = 8080;
console.log("Initializing Server.");
var express = require('express');
var connect = require('connect');
var app = express();
var serv = require('http').Server(app); //.createServer(app);
var io = require('socket.io').listen(serv); //(serv,{});
console.log("Starting Server.");
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(serverPort, function(){
console.log('Server running on ' + serverPort + ' !');
});
app.get('/',function(req, res) {
res.sendFile(__dirname + '/index.html');
});
serv.listen(8081);
var SOCKET_LIST = {};
io.on('connection',function(socket){
console.log("A user is connected");
});
io.sockets.on('connection', function(socket){
console.log('Socket connection');
});
CLIENT
var local = "http://" + document.location.host + ":8081";
var socket = io().connect(local);
In your client code you are using io().connect(local) however the correct way to connect using a specified address with your variable is io.connect(local).
Also, document.location.host will include ":8080" if it is a part of the address you used to obtain the page, therefore you need to remove it. You can try something like document.location.host.split(':')[0]
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//PROBLEM LINE
**app.use(parser.json);**
///////////////
var todos = [];
var nextTodoItem = 1;
app.use(bodyParser.json);
app.get('/', function(req, res){
//console.log("ToDo Root");
res.send("ToDo Root");
});
//GET REQUEST TO GET ALL TODO ITEMS
// GET /todos
app.get('/todos', function (req, res) {
// Need to send back the array of todos
res.json(todos); //array is converted to JSON.
}
);
//GET REQUEST TO GET SOME SPECIFIC TODO
//GET todos/:id
//Express uses : (colon) to parse data.
app.get('/todos/:id', function (req, res) {
var todoID = parseInt(req.params.id, 10);
var todoObjectWithID = -1;
todos.forEach(function (todo) {
if(todo.id == todoID){
todoObjectWithID = todos[todoID - 1];
}
});
if(todoObjectWithID == -1){
res.status(404).send();
} else {
res.json(todoObjectWithID); //Send the JSON of the specific todo with id requested.
}
console.log('Asing for todo with id of ' + req.params.id);
});
//Create a POST request to create new TODO Items.
//POST /todos
app.post('/todos', function(req, res){
var body = req.body;
console.log("description");
res.json(body);
});
//Server basic start up (port and log)
app.listen(3000, function () {
console.log("Server up and running");
});
I run the server with bash (Mac OS) but I go to http://localhost:3000 nothing loads, but when I remove the app.use(bodyParser) it loads properly.
What is the problem in the body-parser?
This problem only occurs when I have that line, otherwise, the server runs up perfectly fine. I need that parser though, so what is my option?
Change that line to app.use(bodyParser.json());
I'm very new to node.js and I'm having struggle with querying to MySQL DB. This is a very simple web page, all I have to do is read the value from the input and search it on my DB.
The problem is that var num is still undefined when the web page executes the query. How do I guarantee that I get that value before executing the query?
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var express = require('express');
var mysql = require('mysql');
var port = process.env.PORT || 8001;
var router = express.Router();
var app = express();
var server = http.createServer(app);
var n_eleitor;
var nome;
var local;
var num_bi;
var num;
// ---- ROUTES ------
app.get('/', function(req, res) { //homepage
res.sendFile(__dirname+'/index.html');
handle_database(req, res);
});
app.get('/result', function(req, res, next) { //results
res.render('result.ejs', { n_eleitor: n_eleitor, local: local, nome: nome });
});
app.use('/', router);
// ---- CONECTION -----
server.listen(port);
var listener = io.listen(server);
listener.sockets.on('connection', function(socket){
socket.on('client_data', function(data){ //receive data from client
//console.log(data.letter);
num_bi = data.letter;
console.log(num_bi);
var num = "'"+num_bi+"'";
console.log(num);
});
});
// ---- MYSQL ------
var pool = mysql.createPool ({ //pool maitains a cache of database connections -> handles multiple connections
connectionLimit : 100,
host : 'localhost',
user : 'root',
password : 'soraia',
database : 'pti2',
});
function handle_database(req, res) {
pool.getConnection(function(err, connection){
if(err){
connection.release(); //connection returns to the pool, ready to be used again by someone else.
return;
}
//console.log('ID:' + connection.threadId);
connection.query("select eleitor.*, freguesia.designacao from freguesia, eleitor where num_bi= ? and freguesia.cod_freg=eleitor.cod_freg",[num], function(err, rows, fields){
n_eleitor = rows[0].cod_eleitor;
nome = rows[0].nome;
local = rows[0].designacao;
connection.release();
console.log(num);
console.log(rows);
});
});
}
When I run the program I get "TypeError: Cannot read property 'cod_eleitor' of undefined" and I think that's because what I said before...
Can someone help me, please?