Use local files in my node.js/socket.io project - javascript

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);

Related

Get request to a .html file is not handled by express

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}!`));

How to run a function in NodeJS and send Response to Client?

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.

Accessing a functions from a js file thats in a public directory

I have a JS file in a folder called public, which also has my CSS file in it. I'm trying to access a function from the JS file (scripts.js), but am having no luck. I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js'. If anyone can help me out, that would be great.
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get('/', function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
var temperature = scripts.converter(data.currently.temperature)
res.render("results", {data: data, temperature: temperature})
} else {
console.log(response.body);
}
});
});
app.get('/results', function(req, res){
res.render("results");
});
app.listen(3000, function(){
console.log("Server has started");
})
scripts.js
module.converter = function(cel) {
var cel = (far - 32) * (5/9);
return cel;
}
exports.data = module;
The path to your module is wrong.
Try var scripts = require("./public/scripts.js"); instead.
You are loading /scripts.js, which is a scripts.js file located at your computers root. To load a file in the current directory, you would do ./scripts.js. In a directory above the current one, it would be ../scripts.js.
If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. directoryname being public in your case

Reactjs serever side stylesheet not working

I am using Reactjs server side. when I implemented style.css file in my project.
but when I run that project then It display error :
So,how can I resolve this. I also try fs: empty in my code then output like this.
So,that didn't work for me.
here, my server.js code
require('babel-register')({presets: ['react']});
var express = require('express');
const fs = require('fs');
var app = express();
app.use(express.static('app'));
var React = require('react');
var ReactDOMServer = require('react-dom/server');
var Home = require('./app/components/index.js');
var AboutUs = require('./app/components/about.jsx');
var Gallery = require('./app/components/gallery.jsx');
var NotFound = require('./app/components/not_found.jsx');
app.get('/', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Home));
response.send(html);
});
app.get('/home', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Home));
response.send(html);
});
app.get('/about', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(AboutUs));
response.send(html);
});
app.get('/gallery', function(request, response){
var html = ReactDOMServer.renderToString(React.createElement(Gallery));
response.send(html);
});
var port =2000; //process.env.PORT;
app.listen(port, function(){
console.log('Listening application at : http://localhost:' + port);
});
Please, help me.

Cannot read property of undefined Node.js

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?

Categories