简体   繁体   English

为什么flask jsonify 返回不明身份?

[英]Why is flask jsonify returning unidentified?

I am using fetch on the frontend to send data to my flask backend in order to make a movie seat booking.我在前端使用 fetch 将数据发送到我的烧瓶后端,以便进行电影座位预订。 The whole process works fine until the client awaits the response, which is "undefined" .整个过程正常工作,直到客户端等待响应,即 "undefined" 。 So , basically the database saves the data , the only problem is the response which is sent to the client.所以,基本上是数据库保存数据,唯一的问题是发送给客户端的响应。 I used jsonify which usually works fine.我使用了通常工作正常的 jsonify。 Can anybody tell me what I am missing?谁能告诉我我错过了什么? Thanks in advance.提前致谢。

Here is the JS code :这是JS代码:

function sendReservationToServer() {

    const selectedSeats = sessionStorage.getItem('selectedSeats')
    const reservation = { userId, selectedSeats, showTimeId, movieHallId }
    fetch('/bookSeats', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(reservation)
    }).then(response => {
        response.json()
    }).then(data => {
        theatreHall.innerHTML = `${data} <br> <a href='/home'>Back to main menu</a>`
        console.log(`${data}`)
    }).catch(err => infoMsg.textContent = err)
    sessionStorage.clear()
}

And this is the flask controller which handles the request:这是处理请求的烧瓶控制器:

@app.route("/bookSeats", methods=["POST"])
def book_seats():
    selected_seats = request.json
    user_id = selected_seats.get('userId')
    seats = json.loads(selected_seats.get('selectedSeats'))
    movie_hall_id = selected_seats.get('movieHallId')
    seat_ids = []
    showtime_id = selected_seats.get('showTimeId')
    for seat in seats:
        seat_ids.append(db.session.query(Seat).filter(
            Seat.seat_number == seat).filter(Seat.movie_hall_id == movie_hall_id).all()[0].stid)
    for seat in seat_ids:
        reserved_seat = ReservedSeat(
            seat_id=seat, show_time=showtime_id, user=user_id)
        db.session.add(reserved_seat)
        db.session.commit()
    reservation = Reservation(
        user=user_id, show_time=showtime_id, number_of_tickets=len(seat_ids))
    db.session.add(reservation)
    db.session.commit()
    message = f'{seats} booked successfully'
    return jsonify(message)

data is undefined because the first then does not return anything. data未定义,因为第一个then不返回任何内容。 Either make it return response.json() or move everything in the second then to the first and replace data with response.json() .要么使其返回response.json()在第二或移动的一切then到第一和替换dataresponse.json()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM