如果您正在使用Docker部署Spring Boot API,可以按照以下步骤设置CORS(跨域资源共享)以解决此问题:
application.properties
# CORS configuration
spring.mvc.cors.allowed-origins= http://localhost:4200
spring.mvc.cors.allowed-methods= GET, POST, PUT, DELETE, OPTIONS
spring.mvc.cors.allowed-headers= *
application.yml
# CORS configuration
spring:
mvc:
cors:
allowed-origins: http://localhost:4200
allowed-methods: GET, POST, PUT, DELETE, OPTIONS
allowed-headers: "*"
修改allowed-origins以匹配您的Angular应用程序的基本URL。
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin': 'http://localhost:8080',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
})
};
将Access-Control-Allow-Origin和Access-Control-Allow-Headers的值更改为Spring Boot API运行的端口和请求的协议。
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('http://localhost:8080/api/users', httpOptions);
}
}
使用上述步骤,您现在应该能够成功地通过Docker容器部署的Spring Boot API与Angular应用程序通信。