我在我当前的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")));
Where __dirname = /rootfolder/app/server/src
当用户访问/端点时:
app.get("/", (req, res) => {
res.sendFile(appRoot.path + "/client/dist/index.html");
});Where appRoot.path = /rootfolder/app
当我访问/端点时,我得到一个状态200,其中包含以下文本:
/rootfolder/app/client/dist/index.html
据我所知,这些文件彼此之间的编码是正确的。有人知道我可能做错了什么吗?
提前感谢!
发布于 2018-04-14 14:27:37
试一试
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目录中。因此,静态根目录/ => /dist/static/data.txt
第二个例子:假设您在dist中有一个名为images的文件夹,您希望仅存储图像。提供路由时,必须使用/images/filename.extension
发布于 2018-04-14 14:28:44
您正在使用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')))
https://stackoverflow.com/questions/49828586
复制相似问题