Node.js 服务express静态文件问题
我在当前的Express应用程序中存在静态文件服务问题,尽管我在其他一些应用程序中也做过类似的设置。。我的文件夹结构如下:Node.js 服务express静态文件问题,node.js,express,static,Node.js,Express,Static,我在当前的Express应用程序中存在静态文件服务问题,尽管我在其他一些应用程序中也做过类似的设置。。我的文件夹结构如下: /rootfolder/ /app package.json /client /dist /static index.html /server /src index.js
/rootfolder/
/app
package.json
/client
/dist
/static
index.html
/server
/src
index.js
myserver/src/index.js的相关部分
:
app.use(express.static(path.join)(\uu dirname,“client”,“dist”))代码>
其中\uu dirname=/rootfolder/app/server/src
当用户点击/
端点时:
app.get("/", (req, res) => {
res.sendFile(appRoot.path + "/client/dist/index.html");
});
其中approt.path=/rootfolder/app
当我点击/
端点时,我得到一个带有以下文本的状态200:
/rootfolder/app/client/dist/index.html
据我所知,这些文件相互之间的编码是正确的。。有人知道我可能做错了什么吗
提前谢谢 试试看
app.use(express.static(path.join(__dirname,'client','dist')));
它基本上获取根目录,并将其与/client+/dist+/static组合,以提供完整的路径,而不是相对路径
现在让我们调用rootdirectory/client/distx,这是静态文件的主目录
如果有其他静态文件但不在同一文件夹中,则必须给出X目录的相对路径
例如:
app.get('/',function(req,res){
res.sendFile('/static/data.txt');
}
在上面的示例中,您指出静态文件(data.txt)位于X/static目录中。
因此=>rootDirectory/client/dist/static/data.txt
第二个例子:
假设您在dist中有一个名为images的文件夹,您只想存储图像。
提供路由时,必须使用/images/filename.extension您使用的是res.send()
而不是
另外,我建议通过path
模块解析路径,而不是串联字符串
const path = require('path')
app.use(express.static(path.join(__dirname, 'client', 'dist', 'static')))
对于/
的响应:
res.sendFile(path.join(uu dirname,'client','dist','index.html'))
如果我理解正确,您就无法访问您的静态文件?是的,正确@amirhosseinrdi如果我的答案或@Kano-answer是正确的,出于礼貌,您能接受答案吗?是的,一旦我锁定它,您就会接受lol@AmirHosseinRdSure,请随意询问您是否遇到任何错误。这给了我Error:enoint:没有这样的文件或目录,stat'/rootfolder/app/server/src/routes/main/client/dist/index.html'
然后修复您的路径:)类似path.join(u dirname',',',',',',',',',',',',',',',',client',dist static')
应该这样做。但我不知道为什么要在app/server/src/routes/main
中为express应用程序设置全局静态文件?通常,这类事情会在主Express文件中处理,该文件通常位于app/server
中。但这取决于您和每个项目,我想。我将sendFile
方法移动到我的app/server/index.js
文件,如上所示。我还更新了我的问题以反映我当前的代码。在提供index.html文件时,您仍然在连接字符串。将其替换为:res.sendFile(path.join(uu dirname。我想这是因为我的index.html
在我的dist
文件夹中,而不是static
。在这种情况下,使用不带“static”的相同命令或将文件移到static文件夹中