登录
首页 >  Golang >  Go问答

Angular 与 Golang 后端无法建立通信的问题

来源:stackoverflow

时间:2024-02-09 15:09:27 271浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《Angular 与 Golang 后端无法建立通信的问题》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在使用 nginx 来提供 angular(index.html) 服务,效果很好。问题是我在尝试与后端通信时不断收到错误。

我的 nginx + angular dockerfile

from node:12-alpine as builder
workdir /usr/src/app
copy . .
run npm install --silent
run npm run ng build --prod

from nginx:latest

copy --from=builder /usr/src/app/dist/frontend /var/www
copy ./default.conf /etc/nginx/nginx.conf

expose 80

cmd ["nginx", "-g", "daemon off;"]

我的 golang dockerfile

from golang:latest

env go111module=on
run mkdir /app
workdir /app

copy go.mod .
copy go.sum .
run go mod download

copy . .

run go build main.go

expose 8000

cmd [ "./main" ]

我的 docker-compose

version: '3.7'
services:
    postgres:
      image: "postgres:latest"
      restart: always
      volumes:
        - ./init.sql:/docker-entrypoint-initdb.d/init.sql
        - data:/var/lib/postgresql/data
      ports:
        - "5432:5432"
      environment:
        - postgres_db=project
        - postgres_user=postgres
        - postgres_password=password
      networks:
        - mynet

    #back-end
    golang:
      build:
        context: .
        dockerfile: dockerfile
      container_name: golang
      links:
        - postgres  
      ports:
        - "8000:8000"
      networks:
        - mynet
    
    #front-end angular application
    angular:
      links:
        - golang
      build:
        context: ./frontend
        dockerfile: dockerfile
      environment:
        - host=golang
      ports:
        - "4200:80"
      networks:
        - mynet

volumes:
  data:

networks:
  mynet:
    driver: bridge

我的 nginx default.conf

worker_processes 4;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        root   /var/www;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

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

        location /users {
            proxy_pass http://golang:8000;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
        }
    }
}

这是我尝试向 golang 发送 api 调用时的结果 [1]:https://i.stack.imgur.com/xquhf.png

我已经被这个问题困扰好几天了,时间已经不多了。请帮忙! 提前致谢。


正确答案


golang:8000 只能在 docker 网络中访问。您可以通过在浏览器中访问 http://35.238.xx.xx:4200/users/xxx 来检查您的 golang API,并在您的角度代码中使用像 "/users/xxx" 这样的相对 URL。

本篇关于《Angular 与 Golang 后端无法建立通信的问题》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>