heroku 在MERN应用程序中创建React应用程序后,路由不工作

kgqe7b3p  于 2022-11-13  发布在  React
关注(0)|答案(1)|浏览(143)

我创建了一个有node.js服务器的MERN应用程序。要在Heroku上托管网站,首先我必须使用npm run build创建一个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'));
   })
}

我使用react-router-dom的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

因此,路由在build index.html文件中不起作用。我希望它能起作用。

k10s72fa

k10s72fa1#

我得到了同样的错误,我做了一个小的变化,我的代码“/”而不是“”,它为我工作的罚款。在这种情况下,我使用的是浏览器路由器,它工作的罚款。

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'));
})
}

相关问题