【问题标题】:Nginx 502 Bad Gateway error when call api调用api时Nginx 502 Bad Gateway错误
【发布时间】:2019-09-15 08:46:49
【问题描述】:

我有一个 Angular 构建和一个 Django 后端,提供在一台服务器上运行的 API。我已经在 nginx 中配置了它们,前端有一个到后端服务器的代理。

后端在 url 127.0.0.1:8000/api 上运行,前端在 localhost 上运行

配置:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        charset utf-8;
        server_name  localhost;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_types text/css text/javascript application/x-javascript application/json;

        location /api {
            proxy_pass http://127.0.0.1:8000/api;
        }

        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

现在,当我从前端进行任何 api 调用时,我会收到 502 Bad Gateway 错误

GET http://localhost/api/posts/post/management 502(错误网关)

【问题讨论】:

    标签: django angular nginx


    【解决方案1】:

    我有更换器配置到

    upstream backend {
          server backend:8000;
        }
    
        server {
            listen 80;
            charset utf-8;
            server_name  localhost;
    
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            include /etc/nginx/mime.types;
    
            gzip on;
            gzip_types text/css text/javascript application/x-javascript application/json;
    
            # backend urls
            location ~ ^/(admin|api|media) {
                proxy_redirect off;
                proxy_pass http://backend;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
            }
    
            # static files
            location /static {
                proxy_pass http://backend;
            }
    
            # frontend
            location / {
                try_files $uri $uri/ /index.html;
            }
    

    一切正常

    【讨论】:

    • 我也经历过这个。频繁地。它来自您的 api conf 还是前端 conf?请帮助tnx
    • @Noah 你能帮忙解释一下哪个代码块可以解决问题吗?
    猜你喜欢
    • 2021-08-03
    • 2018-04-23
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 2018-11-12
    • 2019-09-05
    相关资源
    最近更新 更多