简体   繁体   中英

Why is app.use() not serving up the 'public' directory when I save even though the path is appears to be correct?

I'm following a slightly outdated tutorial on node and express, and my code is identical to the tutorial, but app.use is not serving up the public directory as I wish. When I go to the root localhost:3000 I still see Weather like in the tags on line 19. When I delete it, I don't see anything, including the public directory's index.html file.

在此处输入图片说明

Here is my index.html file:

 <!DOCTYPE html> <html lang="en"> <head> <!-- <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> --> <title>Document</title> </head> <body> <h1>From a static file.</h1> </body> </html>

Here is my app.js script:

 /* nodejs script that will create, configure, and start the server. run script: node src/app.js keep server running: nodemon src/app.js */ const path = require('path'); const express = require('express'); const app = express(); const publicDirectoryPath = path.join(__dirname, '../public'); // abs path to serve // STACKOVERFLOW - WHY ISN'T THIS SERVING UP PUBLIC DIRECTORY? app.use(express.static(publicDirectoryPath)); // serve 'public' directory // create root route app.get('/', (req, res) => { res.send('<h1>Weather</h1>'); }); // create a help route app.get('/help', (req, res) => { res.send([ {name: 'Barack H. Obama'}, {name: 'George W. Bush'}, {name: 'William J. Clinton'} ]); }); // create an about route app.get('/about', (req, res) => { res.send('<h1>About</h1>'); }); // create a weather route app.get('/weather', (req, res) => { res.send({ forecast: 'rain', location: 'Los Angeles' }); }); // port 3000 is common development port, starts server app.listen(3000, () => { console.log('Server is up on port 3000'); // never displays in browser });

it should be public instead ..public like this const publicDirectoryPath = path.join(__dirname, 'public')

As app.js and public share the same parent directory at the same level. So ..public will point out to dir public outside src which is not available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM