【发布时间】:2021-06-01 06:21:55
【问题描述】:
我有以下 fetch() api,但 catch 块无法正常工作。我得到的错误信息是:
SyntaxError: Unexpected token < in JSON at position 0 undefined
但我期待的是:
something went wrong null
这里是 api:
const getBtn = document.getElementById('get-btn')
const postBtn = document.getElementById('post-btn')
const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {'Content-Type': 'application/json'} : {}
})
.then(response => {
console.log(response.status)
if(response.status >= 400 || response == null){
return response.json()
.then(errResData => {
const error = new Error('something went wrong')
error.data = errResData
throw error;
})
}
return response.json()
})
}
const getData = () =>{
sendHttpRequest('GET','http://localhost/async/fetch/data.jsonx')
.then(responseData => {
console.log(responseData)
})
.catch(err =>{
console.log(err,err.data)
})
}
const sendData = () =>{
sendHttpRequest('POST','http://localhost/async/fetch/data.phpx',{
email: 'someemail@gmail.com',
password: 'compas'
})
.then(responseData => {
console.log(responseData)
})
.catch(err => {
console.log(err,err.data)
})
}
getBtn.addEventListener('click',getData)
postBtn.addEventListener('click',sendData)
【问题讨论】:
-
.then(errResData => {如果你想捕获错误,你需要.catch(errResData => {... -
可能是 404,而不是像代码所期望的那样返回 json,而是返回 html?通常 html 文档中的第一个字符是
<,因此会出现错误。 (虽然看data.phpx,可能是<?php) -
我猜
response.json()失败了,而你永远不会catch那个 -
在localhost/async/fetch/data.jsonx 看到你有什么,我很确定那里有一些 HTML 而不是 JSON。
-
@robo Robok 实际的 url 是 localhost/async/fetch/data.json 或 data.php。我在两者上都添加了一个 x 以创建 404 错误
标签: javascript fetch-api catch-block