我在python flask和jquery上有一个应用程序。每当我尝试在某些事件上调用日志记录机制时,我都面临以下问题。我还没有找到可以解决这个问题的stackoverflow的答案
POST http://localhost:5000/uploadLog/[object%20Object] 500 (INTERNAL SERVER ERROR)
在frontend.js文件中:
var eventObj = {
'eventType': 'Type1',
'eventDesc': event.target.href
};
$.post('/uploadLog/'+eventObj, function(response){
alert("successfully logged");
})
在controller.py中:
@app.route('/uploadLog/<eventObj>', methods=['POST'])
def uploadLog(eventObj):
loggerProg.updateLog(eventLogObj)
return jsonify({'status':'success'})
在loggerProg.py中:
def updateLog(eventObj):
parsed_obj = json.load(eventObj)
我试着在一个文件中编写eventObj,然后得到了&#34; [object Object]&#34;在文件中。
答案 0 :(得分:1)
您需要a)在将POST对象发送到服务器之前序列化JavaScript对象,并b)将请求的Content-Type
标头设置为application/json
,如下所示:
$.ajax({
url: "/uploadLog",
type: "POST",
data: JSON.stringify(eventObj),
contentType: "application/json",
success: function() {
alert("Success!");
}
});
然后在服务器上,为方便起见,使用Flask的get_json()
函数解析请求正文:
@app.route('/uploadLog', methods=['POST'])
def uploadLog():
parsed_obj = request.get_json()