【问题标题】:nginx with react-router /api is a 404 page带有 react-router /api 的 nginx 是 404 页面
【发布时间】:2021-12-02 02:20:36
【问题描述】:

我正在制作一个多容器应用程序,前端使用 nginx,后端使用 spring boot。

在添加 nginx 之前,我将 localhost:3000 作为我的 react 应用,将 localhost:8080 作为我的 spring API。在 3000/themes 中,我可以看到反应页面,并且通过 /themes 我可以访问 API,因为 localhost:8080 是包中的代理行.json。

将此适应 docker-compose 上下文我更改为下面的代码,但在 localhost:80/themes 中我只能访问 API,这是预期的。如果我把线 "proxy_pass http://backend;""location /api {}",当访问 localhost/api 时,我会得到我的个性化 404 页面,因为 /api 不是 react-route 中的路由,也不应该是。 我希望有一个非反应路由来服务我的 api,例如代理行中的 "http:backend/api""localhost/themes" 有我的主题页面,并在子组件中访问 "/themes" 并从 localhost:8080/themes 获取此 API,因为我可以从邮递员访问。

我现在的 nginx.conf 是:

upstream backend {
    server app-server:8080;
}

server {

    listen 80;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
        proxy_pass http://backend;
    }
     
    error_page 401 403 404 index.html;   

    location /public {
        root /usr/local/var/www;
    }
}

而我的 package.json 代理行是:

"proxy": "http://backend",

【问题讨论】:

    标签: reactjs nginx docker-compose react-router


    【解决方案1】:

    您可以尝试为proxy_pass 添加一个命名位置,并将其附加为try_files 的最后一个参数

    upstream backend {
        server app-server:8080;
    }
    
    server {
    
        listen 80;
    
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
    
        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
            try_files $uri $uri/ @proxy-backend;    
        }
    
        location @proxy-backend {
            proxy_pass http://backend;
        }
         
        error_page 401 403 404 index.html;   
    
        location /public {
            root /usr/local/var/www;
        }
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2018-07-11
    • 2020-02-13
    • 2016-01-18
    • 2018-05-10
    • 2017-09-26
    • 2018-02-20
    • 2019-01-08
    相关资源
    最近更新 更多