[英]Cannot Get/ when express app is deployed on heroku
my dir structure我的目录结构
/src
--/public
--/server.ts
--package.json
--package-lock.json
above is my director structure以上是我的导演结构
app.use(express.static(__dirname + "/public/"));
// app.use(express.static("/public/"));
const path = require("path");
app.get("/", (req, res, next) => {
// res.sendFile(path.join(__dirname, + "public", 'index.html'));
res.sendFile(__dirname , "index.html");
//res.send('Testing one two');
});
const port = process.env.PORT || '5005';
app.listen(port, () => console.log("Server running on port 5005"));
when I run the above code, it works well on my local machine but won't work when it is deployed to Heroku, I tried just passing a string like this and it worked, but when I want to render a static file like the HTML file it wont work on heroku, any help?当我运行上面的代码时,它在我的本地机器上运行良好,但在部署到 Heroku 时不起作用,我尝试只传递这样的字符串并且它工作,但是当我想渲染 static 文件时文件它不适用于 heroku,有什么帮助吗? i think the problem is my directory structure
我认为问题是我的目录结构
app.get("/", (req, res, next) => {
res.send('Testing one two');
});
If I recall correctly, express.static
middleware is separate from res.sendFile
.如果我没记错的话,
express.static
中间件与res.sendFile
是分开的。 In other words, even if you set express.static
to public
, it will not do anything to res.sendFile
, as it takes the first parameter as a path.换句话说,即使你将
express.static
设置为public
,它也不会对res.sendFile
做任何事情,因为它将第一个参数作为路径。
In my humble opinion, it would be better if you were to use an absolute path, like the following snippet below.以我的拙见,如果您使用绝对路径会更好,如下面的片段。
const path = require('path');
/** Code here... **/
app.get("/", (req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
Explanations:说明:
path.join
is an utility to join path segments into one path. path.join
是将路径段连接到一个路径的实用程序。 It is cross-platform compatible.__dirname
will get the current directory that the script is running from. __dirname
将获取运行脚本的当前目录。 Further reading: Express methods .进一步阅读:表达方法。
Okay so even I Had the same issue Relax, You just need to give the address of the index.html file in the path for the code metioned below and paste this code at the end of the express file and everything will work perfectly fine and you are good to go.好吧,即使我遇到了同样的问题放松,您只需要在下面提到的代码的路径中提供 index.html 文件的地址,然后将此代码粘贴到 express 文件的末尾,一切都会正常工作,您对 go 很好。
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './public/index.html'));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.