BakerShoeMaker
BakerShoeMaker

Reputation: 41

Using ExpressJS: How to use app.use to serve static files vs. app.get()?

I'm using express to serve files and everything is working but I can't get my console.log statement to show in app.get() route statment. I'm currently using app.use(express.static("public")); to serve from the public folder.

Here is the full code:

//Server static files from the public folder.
app.use(express.static("public"));

app.listen(PORT, function(){
console.log("Sever is running and listening on port: " +PORT);
});

//Establish routes
app.get('/', function (req, res) {
//res.sendFile('/student-profile');
res.send("This is the response.");
});

1) How can I get this work?

2) Also, is the index.html the first file that is looked for when serving static files from the public folder?

Upvotes: 2

Views: 236

Answers (1)

Mark
Mark

Reputation: 31

/* directories
public
views
app.js
*/

// create server
const express = require('express');
const app = express();
// import path
const path = require('path');
// use static directory
app.use(express.static(path.join(__dirname, 'public')));

app.get("/", (req, res, next) => {
   res.send("This is the response.")
   // if you want to render a template then
   // in the {} you can send data with

   //res.render("FileName", {})
})

app.listen(PORT, () => {
   console.log("Sever is running and listening on port: " +PORT);
});

Upvotes: 1

Related Questions