代码之家  ›  专栏  ›  技术社区  ›  mobiman

Heroku/Express:尝试访问子路由时“找不到”(刷新时)

  •  0
  • mobiman  · 技术社区  · 6 年前

    我在Heroku上部署了一个React Web应用程序,并在Express/Node.js服务器上运行。当有人试图访问任何路由时,my server index.js文件将运行以下代码:

    const path = require('path')
    app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
    })
    

    当我从根路由(“/”)加载应用程序时,一切都很好,当我在应用程序中导航时(使用React Router),一切都很好。当我尝试从子路由(例如,/contact)刷新时,就会出现问题,然后出现“找不到”错误。当我查看Heroku日志时,我看到这样一条消息:

    Error: ENOENT: no such file or directory, stat '/client/build/index.html'
    

    我还应该注意到,我尝试过其他sendFile配置,但没有成功,例如:

    res.sendFile(path.resolve(__dirname + '/client/build/index.html'))
    

    有人知道问题出在哪里吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   mobiman    6 年前

    我发现问题出在哪里,我只是走错了路。应该是:

    res.sendFile(path.resolve(__dirname + '/app/client/build/index.html'))
    

    添加了“/app”部分