首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MERN应用程序中创建了react应用程序之后,路由就无法工作了。

在MERN应用程序中创建了react应用程序之后,路由就无法工作了。
EN

Stack Overflow用户
提问于 2022-05-13 09:31:24
回答 1查看 87关注 0票数 0

我创建了一个有node.js服务器的MERN应用程序。首先,要在Heroku上托管网站,我必须使用、npm、run build创建一个构建文件夹。之后,我必须将其添加到服务器中的入口点文件中。

代码语言:javascript
复制
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之类的方法。但在我的网站上什么都没用。

然后,从理论上讲,我用本地计算机重新运行后端,因此前端也被托管。前端是通过这个代码连接到后端的。

代码语言:javascript
复制
app.use(express.static("./FRONTEND/build"));
app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname + './FRONTEND', 'build', 'index.html'));
})

因此,我为前端的构建提供服务,并且发现路由在构建中也不起作用。这里出现的错误是

代码语言:javascript
复制
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

因此,路由在构建的文件中无法工作。我希望它能提供任何建议。

EN

回答 1

Stack Overflow用户

发布于 2022-08-28 15:59:10

我也犯了同样的错误,我对我的代码做了小改动,使"/*“代替了"*”,这对我来说很好。在本例中,我使用的是浏览器路由器,在此基础上,它工作得很好。

代码语言:javascript
复制
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'));
})
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72227366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档