需要在 AWS Lightsail 容器中配置正确的端口和协议,并在代码中设置正确的请求地址和端口号。
示例代码(Java Springboot):
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MyController {
@GetMapping("/example")
public String example() {
return "Springboot backend is working";
}
}
示例代码(Angular):
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
baseUrl = 'http://backend.example.com:8080';
constructor(private http: HttpClient) { }
getExample() {
return this.http.get(`${this.baseUrl}/api/example`);
}
}
在上述代码中,backend.example.com
应该替换为你的后端服务地址。如需使用安全连接,请将 http
替换为 https
,并确保正确配置 SSL 证书。
另外,需要在 AWS Lightsail 控制台中打开相应的端口,以便接收来自前端的请求。默认情况下,Springboot 后端会监听 8080 端口。因此,在 AWS Lightsail 中需要添加入站规则,允许来自前端服务的流量通过 TCP 协议访问 8080 端口。