我创建了一个有node.js服务器的MERN应用程序。首先,要在Heroku上托管网站,我必须使用、npm、run build创建一个构建文件夹。之后,我必须将其添加到服务器中的入口点文件中。
app.use(express.static("./FRONTEND/build"));
if (process.env.NODE_ENV == "production") {
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})
}我使用router的BrowserRouter通过网页进行路由。但是当我将这个站点上传到Heroku上时,我发现主页工作得很好,但是当我路由到其他页面时,出现了一个错误,它说应用程序中发生了一个错误。我尝试搜索它,并找到了诸如添加static.json、使用HashRouter和添加.htaccess之类的方法。但在我的网站上什么都没用。
然后,从理论上讲,我用本地计算机重新运行后端,因此前端也被托管。前端是通过这个代码连接到后端的。
app.use(express.static("./FRONTEND/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})因此,我为前端的构建提供服务,并且发现路由在构建中也不起作用。这里出现的错误是
ReferenceError: __dirname is not defined
at file:///D:/Yash/React_websites/housedeck-home-services/BACKEND/index.js:26:29
at Layer.handle [as handle_request] (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\layer.js:95:5)
at D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:281:22
at param (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:360:14)
at param (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:371:14)
at Function.process_params (D:\Yash\React_websites\housedeck-home-services\BACKEND\node_modules\express\lib\router\index.js:416:3)
at next (D:\Yash\React_websites\housedeck-home-services\BACK因此,路由在构建的文件中无法工作。我希望它能提供任何建议。。
发布于 2022-08-28 15:59:10
我也犯了同样的错误,我对我的代码做了小改动,使"/*“代替了"*”,这对我来说很好。在本例中,我使用的是浏览器路由器,在此基础上,它工作得很好。
app.use(express.static("./FRONTEND/build"));
if (process.env.NODE_ENV == "production") {
app.get("/*", (req, res) => {
res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})
}https://stackoverflow.com/questions/72227366
复制相似问题