Raspberry
Raspberry

Reputation: 31

Same content in both html file when sendfile in nodejs express

Hi still new to nodejs and trying create a simple website with two pages. I'm currently having issues that the content of the second file is being rendered as the first one even though the source inspector in the browser says it's looking a the second file.

The server.js is as follow:

const http = require('http');
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.static("express"));
// default URL for website
app.use('/', function(req,res){
    res.sendFile(path.join(__dirname+'/express/index.html'));
    //__dirname : It will resolve to your project folder.
  });

app.get('/avocado', function(req,res){
    res.sendFile(path.join(__dirname+'/express/avocado.html'));
});
const server = http.createServer(app);
const port = 3000;
server.listen(port);
console.debug('Server listening on port ' + port);

while the other two html files it's poinint to in the folder "express" is currently just having real basic html to try to debug easily.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>I start here</p>
</body>
</html>

and avocado.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>I Get to this page fine</p>
</body>
</html>

As said the source inspector in the browser claims to have access to both, but both this cite when locing at / or /avocado will say "I start here"

Upvotes: 1

Views: 32

Answers (1)

Quentin
Quentin

Reputation: 943615

You’ve set up the first handler as middleware with app.use.

It runs before reaching the route for /avocado so will always respond with the index file.

Use app.get for an endpoint. Only use app.use for middleware.

Upvotes: 1

Related Questions