I have been traversing the web for good tutorials on single page apps in Express.js. I have found a lot of different tutorials, and also some scaffolded projects. None of them seems easy to understand for me (they don't provide understanding of fundamentals), and therefore I allowed myself to start with a clean sheet.
I want the server side and client side to be completely decoupled. Therefore I want to serve a static web page with images and css script files and everything I need, and I want the backend to be a REST API. This is not hard:
var express = require("express");
var app = express();
app.use("/", express.static(__dirname + "/public"));
app.get("/api", function(req,res) {
res.send("Test")
})
var port = process.env.PORT || 8080;
app.listen(port);
console.log("Server up on port " + port);
Here I have the beginning structure. One simply serves the "public" directory statically, and all routes to the api on their own. This allows all subfolders of the public/ folders such as for instance public/images to be served as well. index.html is served if you only input server:8080/ and directory listing does not show.
In case of collisions the static files will be served instead of the route. For instance:
app.get("/images/test.gif", function(req,res) {
res.send("Test")
});
...when the file public/images/test.gif exists - the image will be served and not the route.
No comments:
Post a Comment