【问题标题】:Node.js gives 404 error in production with React on Windows ServerNode.js 在 Windows Server 上使用 React 在生产中出现 404 错误
【发布时间】:2021-05-23 09:29:21
【问题描述】:

我使用 MS Azure 来托管一个站点,其中我有一个由 Node 提供的 React 应用程序。 React 内部有用于导航的 Routes。 在开发中,如果我直接转到 localhost:5000/user 它会呈现正确的页面,但在生产中转到 /user 它会给出 404 错误。

这是我的节点代码:

const express = require('express')
const mongoose = require('mongoose')
const path = require('path');
const userRouter = require('./routers/userRouter')
const dataRouter = require('./routers/dataRouter')
const keys = require('./config/keys')

const app = express()

const port = process.env.PORT || 5000


app.use(express.json())
app.use('/node/user',userRouter)
app.use('/node/data',dataRouter)
app.use(express.static(path.join(__dirname, 'build')))

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname,'../../', 'build/index.html'));
});

我认为这是由于 /user 路由没有被指向 react 但不是 app.get('/*'...) 的用途吗?

对此有何建议?

提前致谢

【问题讨论】:

    标签: node.js reactjs azure


    【解决方案1】:

    app.get(/*) 不起作用。因此,您可以使用以下代码:

    app.get('/:op',function(req,res)
    {
        if(String(req.params.op).equals("user"))
        {
            res.sendFile(path.join(__dirname,'../../', 'build/index.html'));
        }
        else
        {
            res.send("I am Foo");
        }
    });
    

    【讨论】:

      【解决方案2】:

      找出问题所在。它是 '../../ 正在寻找 src 目录之外的构建文件夹。 重写如下解决了这个问题

      res.sendFIle(path.join(__dirname, 'build/index.html'));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 2019-07-07
        • 1970-01-01
        • 2014-02-24
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多