삽질을 시작했다.
// name, addr 등의 변수는 앞에서 선언하고 값을 줬습니다. 생략
$.ajax({
dataType:"json",
traditional: true,
type: "POST",
url: "/order",
data: {
"name": name,
"addr": addr,
"code": code,
"phone": phone,
"date": date,
"price": price
},
success: function (response) {
alert(response['msg']);
}
})
위 코드를 열심히 구글링해가며, 블로그들 찾아가면서 아래처럼 바꿨는데,
let myData = {
"name": name,
"addr": addr,
"code": code,
"phone": phone,
"date": date,
"price": price
};
const init = {
method: "POST",
body: JSON.stringify(myData),
headers: {
"Content-Type": "application/json"
},
credentials : "same-origin"
}
fetch('/order', init)
.then(response => {
// 첫번째 then
if(response.status === 200){
return response.json()
} else {
console.log(response.statusText);
}
})
.then(jsonData => {
alert(jsonData['msg']);
})
400, 500 에러만 뜨고 되질 않는 것이었다..
진짜 뭐가 문제지? 한참을 이것저것 삽질을 했는데
분명히 해당 주소로 전송을 하긴 하는 것 같은데, 왜 에러가 나지?
@app.route('/order', methods=['POST'])
def ordersave():
return jsonify({'msg': '주문이 완료되었습니다. 계좌입금 부탁드립니다!'})
전송을 한다는 사실은 이렇게 다른 동작을 다 빼고 바로 return 해주면 에러가 뜨지 않고 정상적으로 반응이 왔기 때문에 확신할 수 있었다.
@app.route('/order', methods=['POST'])
def ordersave():
name_receive = html.escape(request.form['name'])
addr_receive = html.escape(request.form['addr'])
code_receive = html.escape(request.form['code'])
phone_receive = html.escape(request.form['phone']) #앞에 html.escape는 입력값이 특수문자나 이상한 게 들어왔을 때 방어하는 부분
이게 기존 jQuery로 ajax를 보냈을 때 코드 앞부분이었다.
근데 여기서 에러가 날 거라곤 전혀 생각도 못했다.
분명히 jQuery로 보내던 걸 fetch로 바꿔서 보낸 것뿐인데!?
라고 생각했지만, 문제는 바로 여기에 있었다.
fetch로 보낸 데이터는 JSON,
JSON데이터는 request.form
이 아니라 request.get_json()
으로 받아야했던 것.
@app.route('/order', methods=['POST'])
def ordersave():
name_receive = html.escape(request.get_json()['name'])
addr_receive = html.escape(request.get_json()['addr'])
code_receive = html.escape(request.get_json()['code'])
phone_receive = html.escape(request.get_json()['phone'])