Connecting Node.js script to a front-end project - javascript

As a javascript newbie, I want to create a front-end project with a very little backend solution using Node.js.
I have a user inteface with some variables and a button. These variables have to be passed to a simple .txt file(on my filesystem) and overwrite its content. For this, I'm using a nodejs script:
var fs = require('fs');
fs.writeFile('log.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
But I want this to work onClick, whereas this only works from the command-line.
So I have the two following problems:
I want to update the .txt file with the button click. So basically the above written code has to be executed, when I click the button. But I don't understand, how to connect the front-end with this nodejs file.
I want the content to be dynamical. I'm sure, once the first problem is solved, this will be straightforward, but right now I don't know this either.
I'm 100% sure I'm missing something(maybe a web-server, but even then, how?). I did my research but all I found was either an overkill or I didn't even understand it. Any help would be appreciated, a tutorial, an advice or just a keyword, that I can use for my research.

Have a look at express. It's a "Fast, unopinionated, minimalist web framework for node". With this you can build a small webserver:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000); // Webserver is running on port 3000
If you run it and got to your browser on http://localhost:3000, it would print Hello World.
Now what you would do is calling your logging function every time a specific URL is requested.
var fs = require('fs');
function log(text, callback) {
fs.writeFile('log.txt', text, callback);
}
app.get('/', function (req, res) {
log('This is my text', function (err) {
if (err) throw err;
res.send('Replaced!');
});
});
Now when you click the button you need to make an AJAX request to the server (maybe using jQuery).

Node.js doesnt have a built in front-library like some other scripting languages such as Python or VB. To create a node.js your intuition was correct in that you will need your app to expose itself as a web-server.
The popular library to do this is called express and it is very easy to get started.
I suggest that you follow the express quickstart tutorial to get into it.
From here you can wrap your code inside a route of the webserver (say /save) for example
var fs = require('fs');
var express = require('express');
var app = express();
app.get('/save', function (req, res) {
fs.writeFile('log.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
res.send('Replaced!')
});
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
With this example with the dependencies installed opening localhost:3000/save in your browser would cause your code to be run.

Related

ExpressJS serve static files on post request

I need Express server to serve static files (website). It works in my code well:
var express = require('express');
var app = express();
var path = require('path');
var p = path.join(__dirname, '../web/public');
app.use("/files", function (req, res) {
return res.send("I will do something on server");
});
app.use(express.static(p));
app.use('/*',express.static(p));
let port = 80;
var server = app.listen(port);
But when I have a form served by this server, it redirects after submit, and the page displays only something like
Cannot POST /dashboard/
How can I correctly handle post requests within the meaning of serving static files? I tried to add this right before declaring the port:
app.post(express.static(p));
app.post('/*', express.static(p));
But it doesn't work.
PS: my entire page is served (I want that) from index.html. In order to do that, I have in my code that:
app.use(express.static(p));
app.use('/*',express.static(p));
How do I "redirect" post requests to index.html? In this file I have the entire app logic (it is a single page app).
PS2: I really need default submit. Going around that is not a solution for me (I want to offer the user to save their login and password, and without submitting the form, Google chrome will not offer that to users). And on the other side I really need use POST, as the login form is transferring sensitive data...
Any ideas?
Thanks!
There is no file called dashboard so there is nothing for express.static to serve.
To handle that dashboard route, you can do this:
app.post("/dashboard", function (req, res) {
return res.send("I will do something with this post");
});
If you want to redirect 404 traffic to index.html, you can do this after all your route definitions:
app.use("/", function (req, res) {
return res.redirect("/index.html");
});

Express routing does not work with simple test case

I think I am missing some concept with basic routing for Express. See here
I created some simple test code as follows in my server index.js file.
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
In my browser(chrome) URL I type
localhost:3000/foo
to trigger the route but I get no response on the server or client.
I verified localhost:3000 is up and running.
Port is set in a different file as follows:
app.set('port', (process.env.PORT || 3000));
But also I get confirmation in the terminal as follows:
const server = app.listen(app.get('port'), () => {
console.log('DEBUG: express: server up');
});
I am on a campus network that blocks some traffic, but b.c. this is localhost I don't think it should matter.
I don't think you're supplying enough information to correctly debug your issue.
I'd initially ensure that Express is listening on port 3000, double-check this line:
app.listen(3000);
Ideally, this line should be at the bottom of the script.
Response to edit: Yes, this should not matter. localhost is an alias for the system itself. It's a loopback, similar to that of 127.0.0.1.
It seems like you have created two express app, as you have mentioned that you are using two different files, the localhost which you are able to run is the one which has app.listen() code, but this doesn't have the app.get()
I suggest you use a single file for now and try doing it.
Try out the following code, and check now with localhost:3000/foo.
const express = require('express')
const app = express()
const port = 3000
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

Node.js crashing on wrong file path

I just started learning Node.js and Express, and I'm currently trying to build a static file server. My question is: How do I prevent node from crashing every time the user inserts a wrong path?
Here's my code:
var express=require('express')
var fs=require('fs')
var app=express()
var server=app.listen(3000, listening)
console.log('Server Started on Port 3000')
function listening(){
console.log('Listening...')
}
app.use(express.static('website'))
app.get('/search/:page', goTo)
function goTo(req, res){
var data=req.params
fs.createReadStream('./website/'+data.page+'.html').pipe(res)
}
Thank you!
With try-catch your app will try to open the specified path. If it fails, your app will send an error instead of crashing.
Try this:
function goTo(req, res) {
var data = req.params;
try{
fs.createReadStream('./website/'+data.page+'.html').pipe(res);
} catch(err) {
res.send(err);
}
}
Hope it helps.

socket.io not working for simple use case

var app = require("http").createServer(handler); // handler defined below
var io = require("socket.io")(app);
var fs = require('fs');
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + "/index.html",
function (err, data) {
if (err) {
res.writeHead(500);
return res.end("Error loading index.html");
}
res.writeHead(200);
res.end("Hell World");
});
}
io.on('connection', function(socket){
socket.on('dataChanged', function(data){console.log("Hello World")});
})
io.emit('dataChanged', 'this is a test')
//index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('dataChanged', function(data){console.log("Hello World")});
</script>
I am trying to implement this trivial feature but it is not working.Where am i going wrong i dont see the logs. socket events are not registered.
Alright three things here.
1. Your res.end is sending Hell world but it should send data
res.end("Hell World");
should be
res.end(data);
This is because we want to display the index.html file not a hello world
2. Your index.html is calling the socket.io js file wrong
<script src="/node_modules/socket.io/socket.io.js"></script>
should be
<script src="/socket.io/socket.io.js"></script>
This is because you cannot reference a file like that because there is no logic for it in your code. socket.io does however have the logic for it and can be called this way
3. Use emit on the client side
In your index.html change this code
socket.on('dataChanged', function(data){console.log("Hello World")});
to
socket.emit('dataChanged', 'this is a test')
and remove
io.emit('dataChanged', 'this is a test')
from your nodejs file
Now you can see Hello World from your console
When I was trying to create a simple chat using socket.io I had a conneciton problem, I assume that you have the same problem: I've used the same io.connect('http://localhost:8080') but later I tried using the IP address of my computer in WiFi network to connect from other devices (because localhost points to current device) - so the IP address of my computer in WiFi network was 192.168.0.103 -> io.connect('http://192.168.0.103') or io.connect('http://192.168.1.103'). I hope this works (the code was for Front-End side).

NodeJS using node-static and restify together

I'm creating a simple testing platform for an app and have the following code setup as my server.js file in the root of my app:
var restify = require('restify'),
nstatic = require('node-static'),
fs = require('fs'),
data = __dirname + '/data.json',
server = restify.createServer();
// Serve static files
var file = new nstatic.Server('');
server.get(/^\/.*/, function(req, res, next) {
file.serve(req, res, next);
});
// Process GET
server.get('/api/:id', function(req, res) {
// NEVER FIRES
});
It serves static files perfectly, however, when I try to make a call to the /api it just hangs and times out. Imagine I'm missing something stupid here, any help would be greatly appreciated.
node-static is calling next with an error, which means it's never yielding to other handlers.
You can move your other handlers above node-static or ignore it's errors by intercepting it's callback.
I made a working version here: http://runnable.com/UWXHRONG7r1zAADe
You may make yourself sure the api get call is caught by moving the second get before the first. The reason is your api calls routes are already matched by the first pattern.

Categories

Resources