我的请求收到了错误的请求响应。我已经使用在线 JSON 验证器检查了我的字典数据是否正确,并且一切正常。
我的代码如下:
// Parse datetime to timestamp and include data in a dict
let data_dict = {
"stop_date": Date.parse(sup_limit.value),
"start_date": Date.parse(inf_limit.value)
}
// Send the Ajax request
let request = $.ajax({
url: url,
type: 'POST',
data: data_dict,
contentType: 'application/json;charset=UTF-8',
});
后端接收端点:
@dashboard_bp.route('/download_last_test_influx<mode>', methods=['GET', 'POST'])
@login_required
def download_last_test_influx(mode: str):
# Check if request comes from a custom or test event
if mode == 'custom':
start_date = int(request.json.get('start_date'))
stop_date = int(request.json.get('stop_date'))
# Check if time range is valid, if not return server internal error
if stop_date - start_date <= 0:
return jsonify({'message': 'Time range must be grater than 0'}), 500
# Create response header
response = make_response(send_file(spock_comm_mgr
.test_backup_influx_manager
.get_last_test_influx_record(start_date=start_date, stop_date=stop_date)))
response.headers['Content-Type'] = 'application/gzip'
response.headers['Content-Encoding'] = 'gzip'
return response
请求标头:
POST /download_last_test_influxcustom HTTP/1.1
Host: 0.0.0.0:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json;charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 48
Origin: http://0.0.0.0:5000
Connection: keep-alive
Referer: http://0.0.0.0:5000/influx_management
Cookie: *********************
请求负载:
stop_date=1623758400000&start_date=1623708000000
响应消息:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
答案 0 :(得分:1)
您告诉您的服务器,您正在发送 JSON 数据,但请求正文不是 JSON 字符串,而是 url 编码的字符串(因为这是 $.ajax()
的默认行为,当您将对象作为 {{ 1}}).
使用 data
,传递正确的 JSON 正文
JSON.stringify