Flask를 활용한 백엔드 서버 구성
Ajax 요청을 처리하기 위해 파이썬의 Flask 프레임워크를 사용하여 간단한 API 서버를 구축합니다. 먼저 Flask 패키지를 설치한 후 아래와 같이 서버 코드를 작성합니다.
from flask import Flask, render_template, request
server = Flask(__name__)
@server.route("/api/data", methods=["GET", "POST"])
def process_ajax():
print("Ajax 요청 수신 완료")
return "Success"
@server.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
server.run(debug=True)
XMLHttpRequest를 이용한 GET 요청 전송
GET 방식의 경우 데이터를 URL의 쿼리 스트링(Query String)에 포함시켜 전송해야 합니다. 브라우저의 기본 객체인 XMLHttpRequest를 사용하는 방법은 다음과 같습니다.
<button id="btn-get">GET 요청 보내기</button>
<script>
document.getElementById('btn-get').addEventListener('click', function () {
const targetUrl = '/api/data?userId=dev_user';
executeGetRequest(targetUrl);
});
function executeGetRequest(url) {
const xhr = new XMLHttpRequest();
// 요청 초기화: 메서드와 URL 설정
xhr.open('GET', url);
// 상태 변화에 따른 이벤트 핸들러
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log("응답 데이터:", xhr.responseText);
} else {
console.error("오류 발생:", xhr.status);
}
}
};
// 실제 요청 전송
xhr.send();
}
</script>
POST 요청 및 JSON 데이터 처리
POST 방식은 데이터를 요청 본문(Body)에 담아 보냅니다. 특히 JSON 형식을 사용할 때는 Content-Type 헤더를 명확히 설정해야 서버에서 이를 올바르게 해석할 수 있습니다.
<button id="btn-post">POST 요청 보내기</button>
<script>
document.getElementById('btn-post').addEventListener('click', function() {
sendPostData('/api/data');
});
function sendPostData(endpoint) {
const xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
// JSON 통신을 위한 헤더 설정
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("서버 응답:", xhr.responseText);
}
};
const payload = {
id: 1004,
token: "abc-123-xyz"
};
// 객체를 문자열로 변환하여 전송
xhr.send(JSON.stringify(payload));
}
</script>
서버측 데이터 수신 방식
Flask 서버에서는 클라이언트가 보낸 데이터 형식(Form Data 또는 JSON)에 따라 접근 방식이 달라집니다.
@server.route("/api/data", methods=["GET", "POST"])
def process_ajax():
if request.method == 'POST':
# JSON 형식 데이터 수신 시
json_data = request.json
print(f"JSON 수신: {json_data}")
# Form Data 형식 데이터 수신 시
# form_user = request.form.get('userId')
return "Process Complete"
Python requests 라이브러리 사용 시 주의사항
외부 API에 JSON 데이터를 보낼 때, requests.post의 json 파라미터를 사용하면 자동으로 직렬화와 헤더 설정이 이루어집니다. 하지만 공백 없는 엄격한 JSON 형식이 필요할 때는 separators 설정을 활용하는 것이 좋습니다.
import requests
import json
api_url = "http://localhost:5000/api/data"
data_obj = {"key": "value"}
# 불필요한 공백을 제거하여 전송 효율 및 보안 검증 최적화
compact_json = json.dumps(data_obj, separators=(',', ':'))
response = requests.post(
api_url,
data=compact_json,
headers={"Content-Type": "application/json"}
)
XMLHttpRequest Hooking을 이용한 요청 가로채기
디버깅이나 보안 분석 시, 웹사이트가 API 요청을 보내기 전에 데이터를 어떻게 가공하는지 확인하기 위해 open 메서드를 후킹(Hooking)할 수 있습니다.
(function() {
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
console.log(`요청 가로채기 -> 메서드: ${method}, URL: ${url}`);
// 특정 파라미터를 강제로 주입하거나 URL을 수정 가능
if (url.includes("/api/data")) {
url += "&debug_mode=true";
}
return originalOpen.apply(this, arguments);
};
})();
위와 같이 프로토타입을 재정의하면 브라우저에서 발생하는 모든 XMLHttpRequest의 호출 시점을 파악하고 제어할 수 있습니다.