我使用命令 npx create-react-app client
创建了一个 React+Express 应用程序对于 React 和 npx express-generator api
对于 Express 后端。客户端和API都在同一个文件夹下application
.
React应用程序在端口3000上运行,我已将express应用程序的端口更改为使用/bin/wwww
中的端口8000 .
在 Express 应用程序中,我在 routes/testAPI.js
中创建了一条路线,
router.get("/", function(req, res, next) {
res.send(“API is working properly”);
});
在 app.js 文件中,我使用了路由来处理请求,
let testAPIRouter = require("./routes/testAPI");
app.use("/testAPI", testAPIRouter);
现在,在 App.js 文件内的 React 应用程序中,我调用了 API 并更新了 <p>{this.state.apiresponse}</p>
的内容.
App.js 文件,
class App extends React.Component{
constructor(props){
super(props);
this.state = {
apiResponse : "",
}
}
apiCall = () => {
fetch("http://localhost:8000/testAPI")
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount = () => {
this.callAPI();
}
render(){
return(
<div>
<p>{this.state.apiResponse}</p>
</div>
)
}
}
我的问题是在 apache 服务器上部署此应用程序。当我运行 Express 并在不同的端口(3000 和 8000)使用react时。我可以使用 npm run build
构建 React 应用程序这将为 react 创建静态构建文件。但是,我如何构建 Express 应用程序以与 React 一起使用?
是不是将 Express 文件移动到服务器并始终在端口 8000 上运行应用程序?
我已经成功地使用并发同时运行了两者。我可以使用 npm run dev
运行该应用程序。但是如何构建应用程序并从 apache 提供服务呢?
提前致谢。
最佳答案
在你的React应用程序的package.json中使用代理
"proxy": "http://localhost:8000"
并且仅使用路由而不是基本 URL 来获取
fetch("/testAPI")
现在将 React App 文件夹复制到 Express 文件夹 并将此脚本添加到 Express 的 package.json
"scripts": {
"client-install": "npm install --prefix reactapp",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix reactapp",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
现在运行
npm run client-install
仅运行一次
npm run dev
同时运行服务器和客户端
关于javascript - 在 apache 服务器上部署 React (3000) 和 Express (8000) 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63499623/