I'm trying to learn express. I'm using FS to load my HTML Page. The only thing I could find on this with a google search was using ASP.NET instead of Express.
Server.js:
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname+'/')))
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
app.post('/testaction', function(a,b){
console.log(a.body.log);
fs.readFileSync('Logged.html');
});
app.listen(3000);
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
</head>
<body>
<form method="post" action="http://localhost:3000/testaction">
<h1>Log This:</h1>
<input type="text" name="log"/>
<input type="submit", value="Press Me!"/>
</form>
</body>
</html>
In order to serve files you don't have to use fs. Example:
app.get('/', function(req, res, next) {
res.render('index');
});
If you need to redirect, you can use:
res.redirect('/staticFile.html');
Remove these lines:
app.get('/', function(a,b,c){
fs.readFileSync('index.html');
});
This line is middleware and it applies to all routes on every request:
app.use(express.static(path.join(__dirname+'/')))
It's purpose is to serve static files from whatever path you provide. In this case you're serving from the root directory so you can navigate to all your code files like http://localhost:3000/package.json for example.
It applies to all HTTP methods, get post put etc...
When you write app.get('/' you override that middleware with a new route and try serving only one file. Just drop that code and you'll server everything statically from the directory you specified above.
If you don't want to serve your code files, put your static files in a different folder such as "site" and set your static path to that folder, for example:
app.use('/', express.static(__dirname + '/site'));