Server Express does not read file beyond index.html

Asked

Viewed 42 times

0

I created a server with express:

const express = require('express');
const path = require('path');

const app = express();
app.use('/static', express.static('public'));


app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '/index.html'));
})

app.get('/addForm', function (req, res) {
    res.sendFile(path.join(__dirname, '/addForm.html'));
})

app.listen(3001);

It reads all right, but when I added another page (/addForm.html) on the same level as /index.html it can’t read anymore.

This is the current structure:

Estrutura atual do projeto

  • What is the error in the console?

  • I guess I didn’t put all the right way

  • So Virgilio, no error appears on the console, simply states even if the path is wrong

  • The path is the same as index.html, since the two are in the same place, which could be wrong ?

  • Do a test and where you put the index.html, that is, in the app.get('/'... change the index.html for addForm.html and see if it works.

  • how do you start the application in which folder? and which command line?

Show 1 more comment

1 answer

0

It seems that your express.static() is loading index.html for you and is also causing http://localhost:3000/addForm.html works for you. But none of the manually created routes would work because res.sendFile(__dirname, "/addForm.html") does not reference a file in the right directory.

Then, you would need to fix the path to that file:

router.get('/addForm', função (req, res, next) {
   res.sendFile (path.join (__ dirname, "../public", "/addForm.html"), {dotfiles: "allow"});
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.