我在当前的Express应用程序中遇到了提供静态文件的问题,虽然我在其他一些应用程序中做了类似的设置。我的文件夹结构如下:
/rootfolder/
/app
package.json
/client
/dist
/static
index.html
/server
/src
index.js
我server/src/index.js
的相关部分:
app.use(express.static(path.join(__dirname, "client", "dist")));
__dirname = /rootfolder/app/server/src
当用户点击/
端点时:
app.get("/", (req, res) => {
res.sendFile(appRoot.path + "/client/dist/index.html");
});
appRoot.path = /rootfolder/app
当我点击/
端点时,我收到状态200,其中包含以下文字:
/rootfolder/app/client/dist/index.html
据我所知,文件是相对于彼此正确编码的。有谁知道我可能做错了什么?
提前致谢!
答案 0 :(得分:0)
尝试
app.use(express.static(path.join(__dirname,'client','dist')));
它基本上获取根目录并将其与/ client + / dist + / static结合起来,为您提供完整路径,而不是相对路径。
现在让我们调用rootdirectory / client / dist X.这是静态文件的主目录 如果您有其他静态但不在同一文件夹中的文件,则必须从X目录中提供相对路径 示例:
app.get('/',function(req,res){
res.sendFile('/static/data.txt');
}
在上面的示例中,您指示静态文件(data.txt)位于X / static目录中。 因此=> rootDirectory /客户端/ DIST /静态/ data.txt中
第二个例子: 假设您在dist中有一个名为images的文件夹,您只想存储图像。 当你提供路线时,你必须使用/images/filename.extention
答案 1 :(得分:0)
您使用res.send()
代替res.sendFile()
另外,我建议通过path
模块解析您的路径,而不是连接字符串。
const path = require('path')
app.use(express.static(path.join(__dirname, 'client', 'dist', 'static')))
对于/
的反应:
res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html')))