serving html files in node js using express - javascript

actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.
here is the code :
var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});

To send a single file for a specific route use the res.sendFile() function.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});
app.listen(3000);
In case you want to serve all files in a directory use the express.static() middleware
var express = require('express');
var app = express();
app.use(express.static('path/to/my/directory'));
app.listen(3000);

With express u can do something like
//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
app.use(express.static("./file"));
})
server.listen(8000);

Related

How to start expressjs on shared A2hosting?

I have search a lot and I can't seem to start express js app. All I'm getting is 404 error.
Default app.js file which has http server and it works fine.
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
And this is express js code which is not working. giving me 404 error.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
server.listen();
I also tried few other combination as well.
var express = require('express');
var app = express();
app.get('/', (req, res) => res.send('Hello World!'));
var http = require('http');
var server = http.createServer(app);
server.listen();
this one also didn't work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => res.send('Hello World!'));
server.listen();
I also tried expressjs to create it own server and it also didn't work.
const express = require('express');
const app = express();
const port = 80;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I also tried to remove port from app listen and not surprisingly it also didn't work.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen();
I also tried everything from express-js-app-listen-vs-server-listen page but not successful.
This is the error I get
For others with the same A2 Hosting issue, the solution is actually so easy...
The problem with the application running the NodeJS deployment on cPanel. Phusion Passenger does not use the root path as '/', but as '/yourAppURL'. So in your NodeJS code, you have to add the specified AppURLPath to the call when using Express...
e.g.
//Instead of
app.get('/', (req, res) => res.send('Hello World!'));
//Change to
app.get('/YourSpesifiedAppURLPath/', (req, res) => res.send('Hello World!'));

How to call a socket.on() from a separated file

I'm trying to call a socket.on() event from an external .js file and I can't figure out what I'm missing...
I'm using NodeJS with ExpressJS.Below are the files:
app.js(the server file)
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
var io = require('socket.io')(http);
....
//Socket Io functions
const ioObj = require( './library/io.js')(app, express, io);
// This route will be used to print the type of HTTP request the particular Route is referring to
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
....
/library/io.js (sockets file)
module.exports = function(app, express, io){
io.on('connection', async function(socket) {
socket.on('refreshPage', function(){
console.log("page should now be refreshed !!");
socket.emit("refreshPageNow");
});
....
});
}
What I'm trying to do is to call/access the refreshPage event from /library/io.js so I can send further a "refresh webpage" signal.
I tried to do something like :
io.sockets.emit("refreshPage");
and
ioObj.sockets.emit("refreshPage");
But didn't work...

sending html form data to node js

I have the following code
<!--index.html-->
<form id = "lang" action="/myform" method="POST" >
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
and
//index.js
var fileServer = new(nodeStatic.Server)();
var app = http.createServer( function(req, res){
fileServer.serve(req, res);
}).listen(port);
var io = socketIO.listen(app);
io.sockets.on('connection', function(socket) {
console.log('recieved connection ');
// convenience function to log server messages on the client
How do I send data in the textbox with id "lang" over to index.js and store it in some variable?
using express by placing it as a parameter in http.createServer() and executing filsServer.serve(req, res) in a callback:
express = require('express');
app2 = express();
http = require('http');
app2.post('/myform', function(req, res){
console.log(req.body.mytext);
});
var app = http.createServer(app2, function(req, res){
fileServer.serve(req, res);
}).listen(8082);
this obviously wouldn't work because I need the index.html page to load to fill in the form to begin with and by executing the code above, the program is expecting some form data even before the html page can load.
Is there another way I can send the data?
I got it to work. Here's the code:
var express = require('express');
var app2 = express();
var bodyParser = require("body-parser");
var path = require('path');
var socketIO = require('socket.io');
app2.use(bodyParser.urlencoded({ extended: false }));
app2.use(bodyParser.json());
var app = http.createServer(app2);
`var io = socketIO.listen(app);`
app2.use( express.static(__dirname));
app2.post('/form', function(req, res){
var lang = req.body.mytext;
console.log( req.body.mytext);
res.send(lang);
});
app.listen(8081);
Despite having created a server using express, I still needed to create the server using the HTTP module because an express server doesn't work with the socket.io module.
And I had used the express server to take care of my static files.

how to integrate signalmaster to already existing expressjs server

I'm trying to use simplewebrtc in my app, I already have a simple nodejs server with express web framework. But to use simpleWebrtc we have to install signal master. I'm looking at the source code for the server.js file in the signal master package but I can't figure out how to combine this server.js with my already existing app.js file. This is basically my app.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
console.log("connected to index");
});
and this is server.js of signalMaster
/*global console*/
var yetify = require('yetify'),
config = require('getconfig'),
uuid = require('node-uuid'),
crypto = require('crypto'),
fs = require('fs'),
port = parseInt(process.env.PORT || config.server.port, 10),
server_handler = function (req, res) {
res.writeHead(404);
res.end();
},
server = null;
// Create an http(s) server instance to that socket.io can listen to
if (config.server.secure) {
server = require('https').Server({
key: fs.readFileSync(config.server.key),
cert: fs.readFileSync(config.server.cert),
passphrase: config.server.password
}, server_handler);
} else {
server = require('http').Server(server_handler);
}
server.listen(port);
var io = require('socket.io').listen(server);
if (config.logLevel) {
// https://github.com/Automattic/socket.io/wiki/Configuring-Socket.IO
io.set('log level', config.logLevel);
}
etc, etc you can look at the rest by downloading the zip. I thought it would be just replacing server with http, but the server=null doesn't really make sense. All the dependencies are in the directory of the signalMaster unzipped file. I was reading about signalMaster here.
You will need something like this
var os = require('os');
var static = require('node-static');
var http = require('http');
var socketIO = require('socket.io');
var fileServer = new(static.Server)();
var app = http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(2013);
var io = socketIO.listen(app);
io.sockets.on('connection', function (socket){
...
socket.on('join', function (message) {
...
}
...
}
i hope this help u

Node serving blank page

I have an index.html page which is present at:
D:\GITProjects\codelab\complete\step1\index.html
I am trying to execute D:\GITProjects\codelab\complete\step1\server.js file via node:
"C:\Program Files\nodejs>node.exe D:\GITProjects\codelab\complete\step1\server.js"
Server.js code:
var static = require('node-static');
var http = require('http');
var file = new (static.Server)("D:\GITProjects\codelab\complete\step1");
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(2011);
When I go to hit:
http://localhost:2011/
I see empty page. Any idea why?
The console shows "http://localhost:2011/ Failed to load resource: the server responded with a status of 404 (Not Found)"
You need to keep file.serve(req,res) within req.addListener()
var static = require('node-static');
var http = require('http');
var file = new (static.Server)("./");
var app = http.createServer(function (req, res) {
req.addListener('end',function(){ // <--
file.serve(req, res);
}).resume() // <--
}).listen(2011);
Also, you have a couple of other options to go with(if you dont want to stick with node-static)
Option-1: Use fs module to read the file and send it on request
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(2011);
});
Option-2:
Use a web app framework like express(). It provides several great features to simplify the power of node. Then you can either define a specific route for '/' to send your index.html
var express= require('express')
var app = express()
app.get('/',function(req,res){
res.sendFile('index.html',{ root:__dirname })
})
app.listen(2011)
or serve your static assets straightaway:
var express= require('express')
var app = express()
app.use(express.static(__dirname)); //this will make index.html available to every request
app.listen(2011)
__dirname is the directory that the currently executing script is in. Since both server.js and index.html are at same level, __dirname will point to *D:\GITProjects\codelab\complete\step1*

Categories

Resources