繁体   English   中英

在单个 Azure 应用程序中使用 Express 后端反应应用程序(通过 create-react-app)?

[英]React app (via create-react-app) with Express backend in single Azure app?

我有一个带有快速后端的 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 而不是 Z0ECD11C1D7A287401D148A23BBD7A2 响应。 这向我表明它实际上并没有将 Express 端口暴露给前端。

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

事实证明,这种方法——虽然它是错误的——实际上是有效的,但 Azure 应用服务只会公开一个端口。 在这种情况下,我们可以通过 npx 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM