【问题标题】:React app (via create-react-app) with Express backend in single Azure app?在单个 Azure 应用程序中使用 Express 后端的 React 应用程序(通过 create-react-app)?
【发布时间】:2021-04-07 17:23:41
【问题描述】:

我有一个带有 Express 后端的 React 前端应用,它在本地作为代理 API 服务器工作。

在我的本地开发环境中,React 前端运行在 3001 端口,Express 服务器运行在 3000 端口。

在我的package.json 中,我设置了代理:

"proxy": "http://localhost:3000",...

应用通过 Azure 管道进行部署,该管道构建应用和服务器,将它们压缩,然后将人工制品复制到 Azure 域。

在 Azure 应用的配置中,我有以下启动命令:

node server & npx serve -s

这应该(理论上)启动 Express 服务器(设置为侦听端口 3000)并为前端服务。前端确实可以访问,但是当它尝试通过简单的 fetch 请求调用 api 时,它返回的是 React 应用程序的 HTML,而不是 JSON 响应。这表明它实际上并没有将 Express 端口暴露给前端。

是否真的可以将 Express 服务器和前端作为同一容器的一部分提供服务?

【问题讨论】:

    标签: node.js reactjs azure express


    【解决方案1】:

    事实证明,这种方法——虽然它是错误的——实际上是有效的,但 Azure 应用服务只会公开一个端口。在这种情况下,我们可以通过 npx serve -s 公开 React 前端,或者通过将 PORT 变量设置为 3000 公开 api。两者都在运行,但只有一个可以访问。

    解决方案是通过 Express 服务器为 React 前端提供服务:

    const path = require('path');
    const { response } = require('express');
    const express = require('express');
    const request = require('request');
    const app = express();
    
    app.use(express.json());
    
    app.use(express.static(path.join(__dirname, '../')));
    
    app.use('/api', function (req, res, next) {
        // API function calls here
        ...
    });
    
    app.get('*', function(req, res, next) {
        res.sendFile(path.join(__dirname, '../index.html'));
    });
    
    app.set('port', 3000);
    
    app.listen(app.get('port'), () => {
        console.log('Proxy server listening on port ' + app.get('port'));
    });
    

    并将PORT 容器变量设置为3000

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2019-10-15
      • 2019-06-24
      • 2018-07-14
      • 2020-10-08
      相关资源
      最近更新 更多