【问题标题】:How to route React web app to different link from node Js?如何将 React Web 应用程序路由到节点 Js 的不同链接?
【发布时间】:2022-01-08 03:19:38
【问题描述】:

当我通过 nodeJs 加载页面时,它会在 localhost:5000 加载 React 应用程序,但我希望 React 应用程序应该通过不同的链接加载,例如:

http://localhost:5000/api 

server.js的后端代码如下:

app.use(express.json({ extended: false }));

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    next();
  });

  app.use(express.static(path.join(__dirname, "/client", "build")));

  app.get('/', (req, res) => {
    
    res.sendFile(npath.resolve(__dirname, 'client', 'build', 'index.html'));
  });



if (process.env.NODE_ENV === 'production') {
  //static folder
  app.use(express.static('client/build'));
  

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

上面的代码在 localhost:5000 加载,但它应该在 localhost:5000/api 加载。

【问题讨论】:

    标签: node.js reactjs routes backend


    【解决方案1】:

    在正确的位置提供您的react 应用,使用/api 而不是/

    app.use(express.json({ extended: false }));
    
    app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header(
          'Access-Control-Allow-Headers',
          'Origin, X-Requested-With, Content-Type, Accept'
        );
        next();
      });
    
      app.use(express.static(path.join(__dirname, "/client", "build")));
    
      // it's now '/api' instead of '/'
      app.get('/api', (req, res) => {
        
        res.sendFile(npath.resolve(__dirname, 'client', 'build', 'index.html'));
      });
    
    

    这也很方便,只要有人登陆 http://localhost:5000 以被重定向到 http://localhost:5000/api 时添加一个后备位置

    app.get('/', (req, res) => {
        res.redirect('/api')
    })
    
    

    我不确定为什么您在生产时两次提供相同的文件?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 2023-02-02
      • 2013-04-24
      • 1970-01-01
      相关资源
      最近更新 更多