使用FETCH获取JSON解析错误,但不使用PostMan



我已经使用Django和Django -rest-framework设置了一个API端点,使用POST请求提交表单。当使用PostMan发送请求时,后端工作正常,并将数据添加到DB中。但是,当我使用fetch时,后端返回{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}。前端是一个react webpack设置。

这是我用来发出请求的代码:

let csrftoken = getCookie('csrftoken')
const jsonString = JSON.stringify(data,null, '    ')
console.log(jsonString)
const response = await fetch(baseURL + 'jobs/',{
method: 'POST',
mode: 'same-origin',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
'X-CSRFToken': csrftoken,
'Accept-Encoding': 'gzip, deflate, br'
},
body: jsonString
});
return response.json()
}

这是jsonString的打印:

{
"data": "asdf",
"mode": "text",
"node": "sdaf",
"species": "asdf",
"model_type": "proto",
"dry_run": false,
"single_fam_mode": false,
"mail_address": ""
}

我还使用wireshark捕获了PostMan和fetch请求。下面是邮差请求,成功的响应:

[1 bytes missing in capture file].POST /api/jobs/ HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.28.3
Accept: */*
Postman-Token: 8c4b0ff0-5430-4420-8785-e965a808db5c
Host: localhost:8000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 184
{
"data": "asdsadad",
"mode": "text",
"node": "katten",
"model_type": "both",
"dry_run": false,
"single_fam_mode": false,
"mail_address": "test@teast1.no"
}HTTP/1.1 201 Created
Date: Tue, 31 Aug 2021 09:10:32 GMT
Server: WSGIServer/0.2 CPython/3.8.5
Content-Type: application/json
Vary: Accept, Origin, Cookie
Allow: GET, POST, OPTIONS
X-Frame-Options: DENY
Content-Length: 271
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
{"id": "4c6baad3-be1a-4463-8c06-edec51443565", "initiated": "2021-08-31T09:10:32.850533Z", "data": "asdsadad", "mode": "text", "species": "job@09:10:32", "node": "katten", "model_type": "both", "dry_run": false, "single_fam_mode": false, "mail_address": "test@teast1.no"}

然而这是带有400响应的fetch请求:

POST /api/jobs/ HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Firefox/91.0
Accept: */*
Accept-Language: nb-NO,nb;q=0.9,no-NO;q=0.8,no;q=0.6,nn-NO;q=0.5,nn;q=0.4,en-US;q=0.3,en;q=0.1
Accept-Encoding: gzip, deflate
Referer: http://localhost:8000/
Content-Type: application/json
X-CSRFToken: Qv2chVzt4hiDZbe7jYDtUiP7o3IuXzVHnUUc03PYZI8FWKrOCC655rdoaThgQb1B
Origin: http://localhost:8000
Content-Length: 164
DNT: 1
Connection: keep-alive
Cookie: csrftoken=Qv2chVzt4hiDZbe7jYDtUiP7o3IuXzVHnUUc03PYZI8FWKrOCC655rdoaThgQb1B; sessionid=eqh9wotdlhh43ubszv7ievd03fnhh0fl
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: same-origin
Sec-Fetch-Site: same-origin
{
"data": "sadf",
"mode": "text",
"node": "asdf",
"species": "asdf",
"model_type": "proto",
"dry_run": false,
"single_fam_mode": false,
"mail_address": ""
}HTTP/1.1 400 Bad Request
Date: Tue, 31 Aug 2021 10:03:05 GMT
Server: WSGIServer/0.2 CPython/3.8.5
Content-Type: application/json
Vary: Accept, Origin, Cookie
Allow: GET, OPTIONS, POST
X-Frame-Options: DENY
Content-Length: 73
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}

我没有包含任何后端代码,因为我认为它工作正常,因为邮差请求成功。

谁能告诉我我的取回请求是什么问题?

如上所示,尝试urllib3,您的代码可能如下所示:

import urllib3
import json
def get_response():
data = {
"data": "asdf",
"mode": "text",
"node": "sdaf",
"species": "asdf",
"model_type": "proto",
"dry_run": False,
"single_fam_mode": False,
"mail_address": ""
}
try:
encoded_data = json.dumps(data).encode('utf-8')
http = urllib3.PoolManager()
response = http.request(
'POST',
baseURL + 'jobs/',
body=encoded_data,
headers={
'Content-Type': 'application/json',
'Accept': '*/*',
'X-CSRFToken': csrftoken,
'Accept-Encoding': 'gzip, deflate, br'
}
)
return json.loads(response.data.decode('utf-8'))
except:
#Handle your error
pass

我可以建议您尝试传递body而不将其字符串化。我对react.js不太熟悉,但在常规的ajax请求中- json在没有字符串化的情况下原样传递。例如:

const response = await fetch(baseURL + 'jobs/',{
...
body: data
});

解决!这实际上是firefox (v. 91.0.2 Mac OS X)的一个问题。一旦我换成safari或firefox开发者浏览器,它就能工作了。我不知道真正的问题是什么。

最新更新