我有一个网站正在尝试提取一些数据。我正在使用窗口调试器复制获取
fetch("website", {"credentials":"include","headers":{"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3","accept-language":"en-US,en;q=0.9","upgrade-insecure-requests":"1"},"referrerPolicy":"no-referrer-when-downgrade","body":null,"method":"GET","mode":"cors"})
.then(response => {console.log(response)})
这有效,并且我能够在调试器中检查响应。我要访问数据正文:
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: website
__proto__: Response
我读到我需要将它变成这样的json对象:
fetch("website", {"credentials":"include","headers":{"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3","accept-language":"en-US,en;q=0.9","upgrade-insecure-requests":"1"},"referrerPolicy":"no-referrer-when-downgrade","body":null,"method":"GET","mode":"cors"})
.then(response => {console.log(response.json())})
我收到此错误:
[[PromiseStatus]]: "rejected"
[[PromiseValue]]: SyntaxError: Unexpected token < in JSON at position 0
message: "Unexpected token < in JSON at position 0"
我对获取并不了解太多,并试图将获取的内容拼凑起来。
我在做什么错?如何访问body
数据?
答案 0 :(得分:1)
在请求标头中,您指定您将接受text/html
响应。
请尝试改为指定正确的MIME类型application/json
-API应该返回正确的json数据作为响应。
如果您打算将其作为文本来获取,则可以使用response.text()
而不是response.json()
来访问文本数据
(请参阅Response body methods上的获取文档)