我正在try 使用 docker 容器运行角形前端和Golang后端应用程序 它们已成功创建,但当前端try 对后端服务进行任何http调用时,都会失败
获取http://backend:8080/questions net::ERR_NAME_NOT_RESOLVED
通过判断,可以看出前端应用程序正在请求 请求URL: http://backend:8080/questions 推荐人政策: 交叉原点时严格原点
version: "3.8"
services:
frontend:
build: ./question-paper
ports:
- "4200:4200"
backend:
build: ./backend
ports:
- "8080:8080"
environment:
- DB_NAME=questions
- DB_PORT=3306
- DB_HOST=database
- DB_PASSWD=root
- DB_USER=root
depends_on:
- database
database:
image: mysql
restart: always
environment:
MYSQL_DATABASE: questions
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
ports:
- "3806:3306"
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/ # Check the path to init.sql
- my-db:/var/lib/mysql
volumes:
my-db:
和我的Angular 代码
import { HttpClient } from '@angular/common/http';
import { Questions } from '../model/question-model';
import { Observable } from 'rxjs';
import { Inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class QuestionService {
constructor(private httpClient: HttpClient) {}
GetQuestions(): any {
return this.httpClient.get('http://backend:8080/questions');
}
}
后端代码
func main(){
mux := mux.NewRouter()
handle := h.CORS(
h.AllowedOrigins([]string{"*"}),
h.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"}),
h.AllowedHeaders([]string{"Content-Type", "Authorization", "Origin", "Accept"}),
)
mux.HandleFunc("/questions", handlers.GetQuestions)
http.ListenAndServe(":8080", handle(mux))
}
有人能帮我解释一下请求失败的原因吗, 我可以考虑一些解决方案,比如在http url中使用后端服务的IP地址,我认为这不是一个好的 Select