前端(React)不会向 Heroku 上的后端(Spring Boot)发送请求

时间:2021-01-07 18:08:12

标签: reactjs spring-boot heroku

我将前端 (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,
        })
    );
};

在浏览器控制台中,我看到过这样的错误: enter image description here

我尝试在 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,
        })
    );
};

这是显示结果的屏幕: enter image description here

案例#2:然后我将 setupProxy.js 中的目标更改为 Heroku 后端地址:

module.exports = function(app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'https://back-for-app.herokuapp.com',
            changeOrigin: true,
        })
    );
};

这是相同请求的结果: enter image description here

这是控制器的一部分:

@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;
}

UPD2:如果我手动发送请求,后端返回给我的答案的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:0)

好的,我已经想通了。 setupProxy.js 文件仅用于开发。要制作生产代码,我们必须在项目的根目录中创建 static.json 文件。 在我的例子中,这个文件的代码是:

{
    "root": "build/",
    "routes": {
        "/**": "index.html"
    },
    "proxies": {
        "/api/": {
            "origin": "https://back-for-app.herokuapp.com/api"
        }
    }
}

注意地址末尾的/api" - 这部分非常重要。没有这个 /api"