I'm a beginner. What I used was flask and pymongo. If you press the button, it's "Like". It should be +1, but there is a key error at the bottom.
My python route code:
@app.route('/api/like', methods=['POST'])
def like_movie():
title_receive = request.form['title_give']
movie = db.toytoy.find_one({'title': title_receive})
current_like = movie['like']
new_like = current_like + 1
db.toytoy.update_one({'title': title_receive}, {'$set': {'like': new_like}})
return jsonify({'msg': 'like!'})
This is how I POST from JS
function like_movie(title) { $.ajax({ type: 'POST', url: '/api/like', data: {title_give: title}, success: function (response) { console.log(response) alert(response['msg']); window.location.reload(); } }); }
I get an exception as below:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'title_give'
What I want is if it's 'like_btn'. If you press the button, it becomes +1.
The base problem in what you did is not respecting Content-type
. From front JS, you are making a POST with JSON object. Which makes the request to have a content type of application/json
.
In backend code, you use request.form
which expects the request to be in the form encoded types (like application/x-www-form-urlencoded, multipart/form-data
) etc.
So, you need to read the JSON content in backend, instead of reading from a form which is not available. Like below:
ui_req = request.get_json()
title_receive = ui_req['title_give']
And then parse other structures accordingly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.