繁体   English   中英

为什么 app.use() 在我保存时不提供“公共”目录,即使路径似乎是正确的?

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

我正在关注 node 和 express 上的一个稍微过时的教程,我的代码与教程相同,但 app.use 没有按照我的意愿提供公共目录。 当我转到根 localhost:3000 时,我仍然在第 19 行的标签中看到Weather 。当我删除它时,我什么也看不到,包括公共目录的 index.html 文件。

在此处输入图片说明

这是我的 index.html 文件:

 <!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>

这是我的 app.js 脚本:

 /* 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 });

它应该是public而不是..public这样的const publicDirectoryPath = path.join(__dirname, 'public')

由于app.jspublic在同一级别共享相同的父目录。 所以..public将指出src之外的 dir public不可用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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