WEBSERVER JSON API LOCALHOST - json

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.

Related

Is there a way for me to supply the http server in NodeJS with an html file for hosting?

Current code below
const http = require('http');
const server = http.createServer(function(req, res) {
res.setHeader("Content-type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(200);
res.end("Ping server page");
});
server.listen(8080, function() {
console.eblue("\nListening on port 8080");
console.eblue("WEB SERVER STARTED\n");
});
I just want to know if their is a way to make a fully featured site and host it using node.js
I recommend using Express (a node.js package) for web servers, which you can then serve static files - including HTML - through with express.static.
Yes (if I understood correctly), you just need to serve the html as a static file like this:
https://expressjs.com/en/starter/static-files.html

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!

Can nodejs be use on a static website for form submission?

I have this website that right now has a home page and a contact page. The page navigation is done through HTML and href links.
I have also made a server with node.js to handle the form submission on the contact page. It is using express, nodemailer, nodemailer-mailgun-transport for that.
I have been able to get the form submission to work running the node server.js command and going to localhost on my computer. It submits and sends it to my email just fine.
What I am running into, is how can I have that working when I just navigate to my contact page and not using the node command to run the server?
Anything will help.
Several ways you can go about that ...
you have a static HTML page that you want to process form submissions in a NodeJs application
There are 2 smart ways to accomplish such idea
1. You host a NodeJs application
by making use of the express.static(), for example:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const engine = require('./engine');
const app = express();
const PORT = process.env.PORT || 3001;
app.use('/', express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api', async (req, res) => {
res.json(await engine.processForm(req.body));
});
app.listen(PORT, () => {
console.log(`ready on http://localhost:${PORT}`);
});
and your engine.js
exports.processForm = formData => {
// process form...
return { message: 'Email sent', error: null };
};
in this particular example, you should have a directory called public with an index.html file that would contain your form and in that form, upon submission, you could have something like:
<script>
$( "#contactForm" ).submit(function( evt ) {
alert( "Handler for .submit() called." );
evt.preventDefault();
$.post( "/api", $(this).serialize(), function( data ) {
$( ".result" ).html( data.response );
});
});
</script>
You will need to HOST the whole project in a hosting environment that can process NodeJs applications, like Heroku.
2. use Cloud functions, like Google Cloud or AWS Lambda
where you write your NodeJs application as a function, and you will have an HTTP Endpoint to run that function, and you simply add to your form
<form action="https://your.endpoint.com/abcd123" ... >...</form>
either Google Cloud, Azure Functions or AWS Lambda can help you with that
No. Node.js is server-side software: you can't embed it in static webpages.
If you mean "used on a static website" as running the code on the frontend, you can't. What you can do is, if you have a node.js server hosted elsewhere, you can send the form data to this server through a request.
If you want a node.js server only for handling form submissions, it might be a good idea to consider using Cloud Functions.
There is this tutorial on medium that might interest you.

Run Node.js by passing parameters

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