文章内容

2023/3/22 18:02:24,作 者: 黄兵

400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

今天在做测试的时候,向后端提交数据,结果出现了 400 错误,后端监测到的错误内容为:

400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

出现问题的原因:

浏览器(或代理)发送了该服务器无法理解的请求。

也就是服务器需要 json 数据,而浏览器没有发送 json 数据,具体示例代码如下:

response = self.client.post('/dashboard/payssion/order',
                            data=json.dumps({'sku': 1, 'duration': 1}))
self.assertEqual(response.status_code, 200)

后端接收数据的视图:

# 购物支付
plant_id = int(request.json['sku'])
# 订购的月份
duration = int(request.json['duration'])

也就是不能用这种方式获取测试端的数据,由于这个视图是使用 JavaScript 提交的数据,提交的数据类型是 json,所以也需要将测试端改成 json 提交数据。

解决方案:

可以设置 Flask test_client 的提交数据类型为 json,示例代码如下:

response = self.client.post('/dashboard/payssion/order',
                            content_type='application/json',
                            data=json.dumps({'sku': 1, 'duration': 1}))
self.assertEqual(response.status_code, 200)

再次提交,没有出现以上问题。


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

分享到:

发表评论

评论列表