我正在创建一个应用程序,使用MERN堆栈(MySql、Express、React、Node)。前端和后端分别存储在两个单独的Github仓库中,并托管在两个单独的Heroku实例上。前端和后端都成功部署到了Heroku。
问题是如何让前端和后端相互通信?用户应该从调用后端的前端Heroku开始,还是应该从后端开始?
我尝试将前端代理地址设置为后端的Heroku链接,但显然这个代理地址只在开发环境中使用。我尝试向前端添加服务器文件,以消除“无效主机头”错误,但并不能解决通信问题。
下面是前端package.json:
问题是如何让前端和后端相互通信?用户应该从调用后端的前端Heroku开始,还是应该从后端开始?
我尝试将前端代理地址设置为后端的Heroku链接,但显然这个代理地址只在开发环境中使用。我尝试向前端添加服务器文件,以消除“无效主机头”错误,但并不能解决通信问题。
下面是前端package.json:
{
"name": "healthy-front-end",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"express": "^4.17.1",
"materialize-css": "^1.0.0-rc.2",
"moment": "^2.24.0",
"react": "^16.8.6",
"react-datepicker": "^2.8.0",
"react-dom": "^16.8.6",
"react-modal": "^3.9.1",
"react-moment": "^0.9.2",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "react-scripts start",
"dev": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"heroku-postbuild": "npm run build"
},
"proxy": "http://localhost:3001",
"eslintConfig": {
"extends": "react-app"
}
}
这是后端 server.js 文件:
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const env = process.env.NODE_ENV || 'development';
const reactConfig = require(path.join(__dirname, '/config/config.static.json'))[env];
const PORT = process.env.PORT || 3001;
// Define middleware here
app.use(express.static(path.join(__dirname, reactConfig))); // serving react files
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
// Serve up static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
// Routes
require('./controllers/routes')(app);
// Start the API server
app.listen(PORT, () =>
console.log(` ==> API Server now listening on PORT ${PORT}!`)
);
这是带有前端URL的config.static.json文件:
{
"development": "client/public",
"production": "https://healthy-people-front-end.herokuapp.com/"
}
这是添加了生产环境URL的config.js文件:
let config = {
local: {
mysql:{
url: process.env.DB_URL,
},
apiKeys:{}
},
prod: {
mysql:{
url: process.env.JAWSDB_URL,
},
url: 'https://healthy-people-front-end.herokuapp.com/',
apiKeys:{}
}
};
module.exports = config[process.env.APP_ENV || 'local'];
这是后端的package.json文件:
{
"name": "healthy-back-end",
"version": "1.0.0",
"description": "API for HealthMate App",
"main": "server.js",
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "node server.js",
"start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"dev": "concurrently \"npm start\" \"npm run client\"",
"client": "cd ../HealthMate-frontend && npm run start"
},
"author": "",
"license": "ISC",
"dependencies": {
"concurrently": "^4.1.2",
"cors": "^2.8.5",
"dotenv": "^8.1.0",
"express": "^4.17.1",
"hashpass": "0.0.0",
"mysql": "^2.17.1",
"nodemon": "^1.19.1",
"uuid": "^3.3.2"
}
}
如何让两端相互通信?非常感谢您的帮助。