2

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?

3
  • Are you importing express? E.g.: const express = require('express'); const app = express();? Commented Dec 2, 2017 at 1:56
  • Yes, they have been exported. Commented Dec 2, 2017 at 7:15
  • I discovered that you don't need app.get('/') when using express.static('public'); However, you will need a post route method for any POST requests. Commented Dec 4, 2017 at 5:10

1 Answer 1

1
/* 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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.