在金字塔中如何用json数据返回400响应?
我有以下 jquery 代码:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
statusCode: {
200: function (data, textStatus, jqXHR) {
console.log(data);
},
201: function (data, textStatus, jqXHR) {
log(data);
},
400: function(data, textStatus, jqXHR) {
log(data);
},
},
});
当后端(金字塔)验证失败时使用 400。现在,如何从 Pyramid 返回 HTTPBadRequest() 响应以及包含验证错误的 json 数据?我尝试了类似的方法:
response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response
但是当我在 firebug 中检查时,它返回 400 (错误请求),这很好,但它永远不会解析上面 data.responseText 的 json 响应。
I have the following jquery code:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
statusCode: {
200: function (data, textStatus, jqXHR) {
console.log(data);
},
201: function (data, textStatus, jqXHR) {
log(data);
},
400: function(data, textStatus, jqXHR) {
log(data);
},
},
});
the 400 is used when the validation in backend (Pyramid) fails. Now from Pyramid how do I return HTTPBadRequest() response together with a json data that contains the errors of validation? I tried something like:
response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response
But when I inspect in firebug it returns 400 (Bad Request) which is good but it never parses the json response from data.responseText above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,您可能应该首先使用 json 库序列化
error_dict
。鉴于您没有提供有关如何设置视图的任何上下文,我只能向您展示我将如何做到这一点:
如果您想自己创建响应,那么:
要调试问题,请停止基于 jQuery 是否工作并亲自查看请求以确定 Pyramid 是否正常运行,或者是否存在其他问题。
或者甚至只是在浏览器中打开调试器来查看响应中返回的内容。
Well you should probably start off by serializing the
error_dict
using a json library.Given that you don't give any context on how your view is setup, I can only show you how I would do it:
If you want to create the response yourself, then:
To debug the issue, stop going based off of whether jQuery works and look at the requests yourself to determine if Pyramid is operating correctly, or if it is something else that's going on.
Or even just open up the debugger in the browser to look at what is being returned in the response.
我找到了一种简单的方法,比接受的答案更通用,我用这段代码得到了它,我
在我的视图中包含了 exception_response
我在需要的地方引发了 400 异常
在我的异常脚本中,我捕获所有异常以返回通用 json 和我捕获 400 返回特定的 json
I found a simple way to do it more generic then the accepted answer, I got it with this code
I include exception_response in my view
I raise the 400 exception where I need to
In my exceptions script, I trap all exceptions to return generic json and I trap 400 to return a specific json
您可以更改响应状态代码,如下所示:request.response.status_code = 400。以下示例对我有用
You can change response status code like this: request.response.status_code = 400. Following examle is working for me