Home > Enterprise >  When routing "/", console.log does not display any message anywhere in node and express se
When routing "/", console.log does not display any message anywhere in node and express se

Time:06-18

In the code below my problem is that when I do app.get('/', ...) {...} the console.log inside the curly braces does not work, it seems to work only when I comment the part that point to the directory 'website'. The thing is in the '/' route, an HTML page is rendered and I want to pass data to that HTML page but nothing works, I would appreciate some insights.

    // fake data for now
    projectData = { movie: 'Top Gun', score: '5' };
    
    // Require Express to run server and routes
    const express = require('express');
    // Start up an instance of app
    const app = express();
    
    /* Middleware*/
    const bodyParser = require('body-parser');
    //Here we are configuring express to use body-parser as middle-ware.
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    
    // Cors for cross origin allowance
    const cors = require('cors');
    app.use(cors());
    
    // Initialize the main project folder
    app.use(express.static('website'));
    
    // Setup Server
    const port = 8000;
    
    // Make the app listen to the set port
    const server = app.listen(port, listening);
    
    // listening Callback function
    function listening() {
        console.log('Server running on localhost')
        console.log(`Listening to port: ${port}`);
    }
    
    // Messages don't appear inside the get request below
    app.get('/', function (req, res) {
        res.send(projectData);
        console.log('We are here');
    });
    
    // This message show normally for this route
    app.get("/data", function (req, res) {
        res.send(projectData);
        console.log(projectData);
    });

CodePudding user response:

This line of code:

app.use(express.static('website'));

will automatically handle the / route if there is an index.html file in the website directory. So, if you don't want express.static() to handle the / route, then you have multiple options:

  1. Remove index.html from the website directory.
  2. Add the {index: false} option to express.static('website', {index: false}) so that it won't match on the / route.
  3. Move your app.get("/", ...) route BEFORE the express.static() route so that your custom handler matches the route first.
  • Related