<aside>
📌 가게의 주문 정보 페이지에서 주문확인, 배달확인 버튼을 누를시에 API GATEWAY 를 거쳐 주문정보의 상태변경이 Lambda에서 처리가 되고 변경완료 응답을 EC2의 컨트롤러로 보내고 그 다음 FETCH에 대한 응답을 처리 했으나 CORS 문제가 발생 했습니다.
CORS 문제를 해결하기 위해 응답해더에 Access-Control-Allow-Origin
를 사용하여 CORS 오류는 해결 했으나 컨트롤러로의 응답이 오지 않았고 그래서 처음 API GATEWAY 호출 했던 FETCH 요청이 성공하면 클라이언트 쪽에서 다시 컨트롤러를 호출 하도록 변경하였습니다.
</aside>
try {
String orderId = input.getQueryStringParameters().get("orderId");
Long id = Long.valueOf(orderId);
Map<String, String> headers = input.getHeaders();
orderRepository.updateOrderState(id);
// vConnection 의 요청이 EC2 의 컨트롤러로 제대로 응답이 오지 않았다.
// String vAdress = "http://ec2-16-171-161-233.eu-north-1.compute.amazonaws.com:8080/api/lambda/" + orderId;
// URL vURL = new URL(vAdress);
//
// HttpURLConnection vConnection = (HttpURLConnection) vURL.openConnection();
// vConnection.setRequestMethod("GET");
// vConnection.disconnect();
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
responseEvent.setStatusCode(200);
responseEvent.setHeaders(Collections.singletonMap("Access-Control-Allow-Origin", "*"));
responseEvent.setBody();
return responseEvent;
} catch (Exception e) {
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
responseEvent.setStatusCode(400);
return responseEvent;
}
<script th:inline="javascript">
async function confirmOrderWithSSE(orderId) {
const url = 'https://4j6zo6zdmd.execute-api.ap-northeast-2.amazonaws.com/connect_sb/api/see/user/test?test=' + orderId;
const jwtToken = document.cookie;
try {
const response = await fetch(url, {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"Authorization" : jwtToken
}
});
if (response.ok) {
console.log('서버 응답이 성공했습니다.');
alert("서버 응답 성공")
setupSSE(orderId)
// 실제 내용은 response.body 등을 통해 접근할 수 없음
} else {
console.error('서버 응답이 실패했습니다. 응답 상태 코드:', response.status);
}
// 추가 작업 수행
} catch (error) {
console.error('Fetch 요청 중 에러가 발생했습니다.', error);
}
// 람다 처리가 정상적으로 수행 됐을 때 클라이언트 쪽에서 컨트롤러를 호출한다.
function setupSSE(orderId) {
const eventSource = new EventSource('/api/sse/'+ orderId);
eventSource.onmessage = function (event) {
alert("주문이 완료되었습니다")
location.reload();
};
eventSource.onerror = function (error) {
console.error('EventSource failed:', error);
};
}
}
</script>
<aside> 📌 코드를 보면 람다의 호출이 끝나고 클라이언트 측에서 EC2의 컨트롤러를 다시 호출 하게 되는데 이렇게 되면 불필요한 코드가 클라이언트 측에 노출이 되어 웬만하면 람다에서 EC2의 컨트롤러로 바로 요청 되도록 하고 싶었는데 이 부분이 잘 해결되지 않아 보완해야할 부분이라고 생각됩니다.
</aside>