Javascript 如何在node.js express中访问我的公用文件夹中的文件
我正在尝试使用express访问位于公用文件夹中的文件。 我的文件结构如下所示Javascript 如何在node.js express中访问我的公用文件夹中的文件,javascript,node.js,express,Javascript,Node.js,Express,我正在尝试使用express访问位于公用文件夹中的文件。 我的文件结构如下所示 /app -app.js /routes -index.js /public /images /misc -background.jpg /css -style.css 我的app.js正在端口3000上运行 index.js找不到background.jpg或style.css router.get('/',函数(req,res){ res.send(` 韦洛姆 一些文字`)
/app
-app.js
/routes
-index.js
/public
/images
/misc
-background.jpg
/css
-style.css
我的app.js正在端口3000上运行
index.js找不到background.jpg或style.css
router.get('/',函数(req,res){
res.send(`
韦洛姆
一些文字`);
});
module.exports=路由器;
我正在查看文档,所以我不知道这为什么不起作用。由于你的
app.js
和public
文件夹在app文件夹中,你不需要将app
文件夹包含在express.static('app/public')
中,也可以使用path。如下解析
var path = require('path');
app.use(express.static(path.resolve('./public')));
另外,将下面的href
值更改为href=“/css/style.css”
需要app.js中的路径模块:
var path=require('path');
app.use(express.static(path.join(__dirname,'public')));
<link rel="stylesheet" type="text/css" href="/css/style.css">
修改静态内容的中间件:
var path=require('path');
app.use(express.static(path.join(__dirname,'public')));
<link rel="stylesheet" type="text/css" href="/css/style.css">
链接到您的css,如下所示:
var path=require('path');
app.use(express.static(path.join(__dirname,'public')));
<link rel="stylesheet" type="text/css" href="/css/style.css">
因此,如果您转到http://localhost:3000/css/style.css
,您到底得到了什么?无法得到/css/style.csi在我的回答中向您解释了上述原因。它需要绝对路径。因此,可以使用path.resolve将当前路径转换为绝对路径。当前路径应为app.js文件和公用文件夹的相对路径。