【问题标题】:Express Routes for ejected create-react-app弹出的 create-react-app 的快速路由
【发布时间】:2018-09-04 23:02:12
【问题描述】:

我想为路由“/about”提供另一个静态页面, 现在我有:

app.use(express.static(path.resolve(__dirname, '..', 'build')));

app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
app.get('/about', function (req, res) {
    console.log("here")
  res.sendFile(path.resolve(__dirname, '..', 'build', 'about.html'));
});

我也有发帖请求

app.post('/getfrontpage', (req, res) => {
    console.log("FIRST PAGE", req.body.params.page)
});

post 请求有效,我用 axios 拨打电话,但是当我更改 url 时“/about”路由不起作用

【问题讨论】:

  • 嗨,很难说。我看到你有一个反应前端。如果不使用哈希路由,您的反应前端路由必须与 express api 完全相同。另一种选择可能是将您的 api 函数数组传递给 '/' 上的 app.use 并使用 next() 调用堆栈中的下一个函数。 - 真相就在那里
  • 您也可以尝试让另一个 app.use 在 '/about' 路由上专门为静态文件提供服务,然后使用 next() 调用回调以发送文件。希望这可以帮助。 - 真相就在那里

标签: reactjs express static routes router


【解决方案1】:

服务器端有错误吗?

上面的例子对我有用:https://runkit.com/dionnis/5ab936152f32d7001211d85f

注意:我把app.post('/getfrontpage'改成了app.get('/getfrontpage'

【讨论】:

  • 我没有任何错误,但我看不到console.log(“here”),我仍然看到index.html而不是about.html,我认为由“create react app”创建的 webpack 问题
  • 用于“创建反应应用程序”的 Webpack 和 express 应用程序是完全不同的东西。您可以先手动创建“about.html”文件并打开它来测试 express 应用程序吗?
  • 我有 about.html 文件,但每次尝试获取“/about”时,我仍然看到 index.html 内容
  • 尝试更改app.get('/',app.get('/about'的顺序stackoverflow.com/questions/32603818/… BTW:不要忘记在任何更改后重新启动服务器。
  • 更改顺序不起作用,但如果我完全删除 app.get('/') 就可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 2021-02-28
  • 2017-02-08
相关资源
最近更新 更多