我将前端 (ReactJS) 和后端 (Spring Boot) 作为两个不同的应用程序(具有不同的地址)部署到 Heroku。前端链接:https://front-for-app.herokuapp.com。后端链接:https://back-for-app.herokuapp.com。在 React 文件 setupProxy.js 中写了一个后端地址:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://back-for-app.herokuapp.com',
changeOrigin: true,
})
);
};
我尝试在 package.json 中编写甚至代理:
"proxy": "https://back-for-app.herokuapp.com",
请告诉我 - 如何将来自前端(在 Heroku 上)的请求重定向到后端? 在 setupProxy.js 中进行配置后,我可以将请求从前端(在我的本地机器上)发送到 Heroku 上的后端。
UPD:案例 #1 - 来自 localhost (localhost:3000) 的客户端向 localhost (localhost:9090) 上的后端发送请求。 setupProxy.js(没有 createProxyMiddleware):
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:9090',
changeOrigin: true,
})
);
};
案例#2:然后我将 setupProxy.js 中的目标更改为 Heroku 后端地址:
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://back-for-app.herokuapp.com',
changeOrigin: true,
})
);
};
这是控制器的一部分:
@CrossOrigin(origins = "https://front-for-app.herokuapp.com")
@RequestMapping(value = "/api/get/all", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List getFileList() {
return fireService.getAll();
}
这里是从数据库中获取所有文件的方法:
@Transactional
public List getAll() {
Session session = sessionFactory.getCurrentSession();
List list = session.createQuery("SELECT FE.fileName FROM FileEntity AS FE ")
.list();
return list;
}
答案 0 :(得分:0)
好的,我已经想通了。 setupProxy.js
文件仅用于开发。要制作生产代码,我们必须在项目的根目录中创建 static.json
文件。
在我的例子中,这个文件的代码是:
{
"root": "build/",
"routes": {
"/**": "index.html"
},
"proxies": {
"/api/": {
"origin": "https://back-for-app.herokuapp.com/api"
}
}
}
注意地址末尾的/api"
- 这部分非常重要。没有这个 /api"