When using ExpressJS with NodeJS you can use app.get
and app.use
for several useful aspects.
After initializing your App like let app = express();
, you can find below some examples:
app.use(...)
As you correctly pointed, it is useful for "middlewares", it will apply to all the GETs, POSTs, etc. you indicate afterwords. For example, you can use a Middleware only before the GETs you want to be "with user/pass authentication".
Indicate the folder for static contents: app.use(express.static(__dirname + "/public"));
Including a parser for JSON contents: app.use(bodyParser.json());
Define the "Cookie Parser" signing string: app.use(cookieParser("Signing text example"));
Separate Routers for your URLs in different files: app.use("/api", apiRouter);
or app.use("/news", newsRouter);
or app.use("/", siteRouter);
For a custom error handler: app.use(sites404handler);
or app.use(globalErrorHandler);
app.get(...)
When talking about app.get(...)
you are indicating which URLs will be visited via a GET method. But you can use several options here:
Indicate you have a home page: app.get("/", function(req, res) { res.send("Hello world!"); });
Accept POST requests: app.post("/", function(req, res) { res.send("Hello world! With POST call."); });
You can also separate it in another file as "apiRouter.js" and include there: let router = express.Router(); router.route("/books").get(function(req, res) { res.send("/api/books/ called via a Router"); });
app.set(...)
Remember that you also have the option app.set(...)
. This is useful for example to define View Engines like Handlebars (.hbs files).
Hope this can help!