Run Node.js by passing parameters - html

I have a server running with Node.js and my question is, whether it's possible when running the server like I usually do (with the command node app.js) to pass parameters (eg. [UserID; IterationID;ProfileID]). Later I want to use these parameters to generate canvas (which I'm not sure how to read the parameters).
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendfile('main.html');
});
app.listen(port, function(){
//console.log('server is running on ' + port);
});
app.post('/submit', function(req, res){
console.log(req.body.rank);
return res.sendfile('success.html');
});
Thank you very much in advance!

You can pass the environment parameters. Here is linux terminal command example:
YOUR_PARAM=param_value YOUR_PARAM2=param_value2 node app.js
Inside the code you can access those params inside process.env object:
console.log(process.env.YOUR_PARAM); // "param_value"
console.log(process.env.YOUR_PARAM2); // "param_value2"
This is usually done to define where application is running (local, development server, production server).
In my opinion it is the best to put the rest of the configuration in the JSON files and load them according to the application environment.
So basically first you define where your app is running and then based on that load the correct configurations from specified file. That way you can even share the configuration with the rest of the team over git.
P.S.
It is also worth mentioning that convention is to define process.env variables with capital letters in order to avoid overwriting some of the nodejs or system environment variables (if you console.log the process.env object you will see lot of configuration data in there).

Related

socket.io undefined and refusing connection

I am using socket.io to display a message but when I run node server.js it does not console log any of the output message. I have attached my chat.html, server.js and main.js file to show the socket.io code.
chat.html
<script src="http://localhost:54159/socket.io/socket.io.js"></script>
<script src="js/main.js"></script>
server.js
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('New web socket connection...');
socket.emit('message', 'Welcome to Chat Room!');
});
const PORT = 54159 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
main.js
const socket = io();
OK, I guess I'll summarize the recommended changes our exchange in the comments:
Change this:
<script src="http://localhost:54159/socket.io/socket.io.js"></script>
to this:
<script src="/socket.io/socket.io.js"></script>
That removes the need for you to specify the port (which was incorrect anyway).
Change:
/public/chat.html
to:
/chat.html
so that it matches up with where your express.static() line is looking. For /public/chat.html to work, chat.html would have to be located in public/public/chat.html on your server's hard drive, but I assume it's not and it's likely in public/chat.html. Your express.static() line is pointing at public so that's the top of the tree it looks in. Any other paths in the URL are relative to that.
And, anytime you make a change in client or server code, make sure and restart your server to make sure all recent changes are being used.
If you're unsure at all about what port your server is running on, then look at the results of this when your server starts up:
console.log(`Server running on port ${PORT}`)
That will tell you port its running on. The brackets log reference to a port is probably brackets connected to the nodejs debugger which will be on a different port from your web server.

How to link Node.js Post script to HTML form?

I have created a REST full APi, which works as I would be expecting if I am running Postman. I run the Test from an index.js file which would have the routes saved as per below file.
const config = require('config');
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
const express = require('express');
const app = express();
//mongoose.set();
if (!config.get('jwtPrivateKey'))
{
console.log('Fatal ERRORR: jwtPrivateKey key is not defined')
process.exit(1);
}
mongoose.connect(uri ,{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(()=>console.log('Connected to MongoDB...'))
.catch(err=> console.log('Not Connected, bad ;(', err));
app.use(express.json());
//THis is only for posting the user, e.g. Registering them
app.use('/api/users', users);
app.use('/api/auth', auth);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
The real code is happening here. Testing this in Postmon I could establish, that the values are saved in MongoDB.
router.post('/', async (req, res) => {
//validates the request.
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({email: req.body.email});
if (user) return res.status(400).send('User Already Register, try again!');
user = new User(_.pick(req.body, ['firstName','lastName','email','password','subscription']));
const salt = await bcrypt.genSaltSync(15);
user.password = await bcrypt.hash(user.password, salt);
//Here the user is being saved in the Database.
await user.save();
//const token = user.generateAuthToken();
//const token = jwt.sign({_id: user._id}, config.get('jwtPrivateKey'));
const token = user.generateAuthToken();
//We are sending the authentication in the header, and the infromation back to client
res.header('x-auth-token',token).send( _.pick(user, ['_id','firstName','lastName','email','subscription']));
});
Now my question's are:
How can I call the second code block from a , in one particular html file. When using Action="path to the users.js", the browser opens the js file code but doesn't do anything.
Do I need to rewrite the Post block part so that it would as well include the connection details to the DB? And would this mean I would keep open the connection to MongoDB once I insert Read etc.? Wouldn't this eat a lot of resources if multiple users would e.g. log in at the same time?
Or is there a way how I can use the index.js + the users.js which is refereed in the index.js file together?
All of these are theoretical questions, as I am not quite sure how to use the created API in html, then I created as walking through a tutorial.
Do I need to change the approach here?
After some longs hours I finally understood my own issue and question.
What I wanted to achieve is from an HTML page post data in MongoDB through API (this I assume is the best way how to describe this).
In order to do this I needed to:
Start server for the API function e.g. nodemon index.js, which has the information regarding the API.
Opened VS Code opened the terminal and started the API server (if I can call it like that)
Opened CMD and startet the local host for the index.html with navigating to it's folder and then writting http-server now I could access this on http://127.0.0.1:8080.
For the register.html in the form I needed to post:
This is the part which I didn't understood, but now it makes sense. Basically I start the server API seperatly and once it is started I can use e.g. Postmon and other apps which can access this link. I somehow thought html needs some more direct calls.
So After the localhost is started then the register.html will know where to post it via API.
Now I have a JOI validate issue, though on a different more simple case this worked, so I just need to fix the code there.
Thank You For reading through and Apologize if was not clear, still learning the terminology!

WEBSERVER JSON API LOCALHOST

I want setup a simple webserver using JSON API(I Followed this tutorial).I have in this directory (C:\xampp\htdocs\server) 2 files:
server.js
node_modules(folder)
server.js
var express = require('express');
var app = express();
app.listen(3000, function() {
console.log('Chatfuel Bot-Server listening on port 3000...');
});
app.get('/*', function(req, res) {
var jsonResponse = [];
jsonResponse.push({ "text": "Hi. " + (Math.random() * 5 + 1).toFixed(0) + " is a lucky number..." });
res.send(jsonResponse);
});
So what is happening in the background?
After launched via terminal: node server.js
If the server gets a request it invokes code lines 8 to 12.
But it doesn't works! why?
Screens and more info here.
The problem is that you're serving node from your local computer, and the chatbot testing service is trying to connect to that running instance of node, and it cannot connect to your localhost.
In the example, they've used digital ocean to deploy the node application. Therefore, the running API is available at some real IP address.
So, if you want to do what they've done, deploy your node app somewhere and expose that particular deployment's IP to your testing framework, and then it should work.

Setting up URL base for JSON with expressjs

I am completely new to node ExpressJS and am required to rewrite a rule for my server data source (jason format).
./
../public/
/public/css
/public/js
/public/index.html
../datasource/
/datasource/carmodel.json
The default static directories are set in:
app.use(express.static(__dirname + '/../public'));
The above work and everything runs under the 3000 port fine locally.
I need to rewrite the URL for my json file (datasource/carmodel.json) by replacing datasource with car/models/. However my application is unable to find the /datasource/carmodel.json file. I have attempted to recreate this via the following:
app.use('car/models/', require('./../datasource/'));
But I still cannot find the json source URL. It does not matter if I type: http://localhost:3000/car/models/carmodel.json or http://localhost:3000/datasource/carmodel.json for that matter. Is there something I am missing?
------------------
EDITED
------------------
Please see my project structure:
./
node_modules/
public/
css/
custom.css
js/
app.js (angular)
index.html
datasource/
carmodel.json
index.js (express file)
package.json
README
Currently my static folder is running of localhost:3000/. Contents of datasource/index.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
//json
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = 'server/' + filename;
res.download(fileDir);
})
app.listen(3000, function(){
console.log('App started on port 3000!');
});
check something like this:
app.get('/car/models/:filename', function(req, res){
var filename = req.params.filename;
var fileDir = __dirname + '/datasource/' + filename;
res.download(fileDir);
})
then this http://localhost:3000/car/models/carmodel.json should work. I dont test it, youst write from head, therefore there may be some typos.
My solution is not safe. You shoud validate 'filename' before production use (all data from user must be validated).

Express routing returns undefined randomly

I am trying to learn Express with NodeJS and would like to render my views with plain HTML. I hacked together a webserver based on the Express API documentation and several Stack questions, particularly the answer by Andrew Homeyer in this question which states
You can have jade include a plain HTML page:
in views/index.jade
include plain.html in views/plain.html
... and app.js can still just render jade:
res.render(index)
My directory structure looks like this
Project
*web.js
Public
img
js
lib
gallerific
*jquery.opacityrollover.js
*jquery.gallerific.js
angular
theme
views
partials
*index.html
*index.jade
and my server looks like this.
var express = require('express'),
jade = require('jade');
var app = module.exports = express();
app.configure(function(){
app.set('views', __dirname + '/public/views');
app.use("/public/lib", express.static(__dirname + "/public/lib"));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.set('view engine', 'jade')
app.use(express.bodyParser());
});
app.get('/', function(req, res) {
res.render('index');
});
app.get('/partials/:name', function(req, res){
var name = req.params.name;
res.render('/public/partials/' + name);
});
app.get('/public/data/:name', function(req, res){
var name = req.params.name;
res.json('/public/data/' + name)
});
app.listen(3000, function(){
console.log("Express app listening on port %d in %s mode", this.address().port, app.settings.env);
});
What I am seeing is that certain files fail to load from directories in which everything else loads just fine. For example, my Gallery page fails to load the jquery.gallerific.js javascript file from my lib/gallerific directory while it does load the jquery.opacityrollover.js. I have poked around with Chrome Developer Tools and see the following
I had this site working with the Angular Bootstrap webserver so it doesn't seem to be a javascript error with the client side code. Does anyone know what I might doing that would cause this problem?
The source is available at https://github.com/jamesamuir/express-simple-html.git
I figured it out. It turns out I had to resolve paths that I had forgotten about so that Express could render them correctly. It wasn't that the Gallerific javascript library didn't load, it was throwing an error on the image source of undefined for my gallery images (I am pulling them from a JSON file).
Once I put the appropriate paths in for the images and the data file, everything started working again. Thanks to everyone who provided a suggestion for me. It really helped me to work through the problem.