【发布时间】:2015-05-21 10:53:20
【问题描述】:
在我正在制作的一个非常基本的测试网络应用程序中,我在提交表单时使用 angular 来运行一个函数。该函数将数据异步发布到我构建的一个简单 api 中,该 api 应该根据它接收到的 POST 信息将数据输入到数据库中。 POST 似乎在前端正常工作,但是我根本无法从 Flask 访问 request.json 或获取任何发布数据。我觉得这个问题可能是我忽略的简单问题,但到目前为止我根本无法弄清楚。以下是部分代码:
AngularJS:
$scope.submitAddMsg = function (){
var data = {'author': $scope.msgauthor, 'message': $scope.msgmsg};
$http.post('/addMessage', data, {headers: {'Content-Type': 'application/json'}}).
success(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
alert(JSON.parse(data));
});
};
/addMessage 的 Flask 视图功能
@app.route('/addMessage', methods=['POST'])
def addMessage():
#results in 'None type not iterable'
#response = request.form.get('author')
#results in a 400 error
#response = request.get_json()
#results in a 400 error
#response = request.get_json()
#results in 'author' not defined
#name = request.args.get('author')
#return jsonify(author = author)
return str(jsonify(response))
我无法停止收到错误,好像请求不是我认为的那样,我应该做些什么来正确处理这个问题?因为在使用 Angular 发送 POST 甚至带有有效负载的 REST 客户端时,我无法访问任何 POST 信息,而 Angular 是如何发送数据的。
这是 JavaScript 控制台,可以查看 data、status、headers 和 config 最终在 POST 之后运行的成功函数中:
<Response 46 bytes [200 OK]>
testbase.js:53 200
testbase.js:54 function (c){a||(a=Xc(b));return c?(c=a[z(c)],void 0===c&& (c=null),c):a}
testbase.js:55 Object {method: "POST", transformRequest: Array[1], transformResponse: Array[1], headers: Object, url: "/addMessage"…}data: Objectheaders: ObjectAccept: "application/json, text/plain, */*"Content-Type: "application/json"__proto__: Objectmethod: "POST"transformRequest: Array[1]transformResponse: Array[1]url: "/addMessage"__proto__: Object
非常感谢任何有关使其正常工作的帮助,如果您需要更多信息,请告诉我
【问题讨论】:
标签: javascript python angularjs post flask