JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
let res_url = "http://api.techbrood.com/v1/threeds?q=%E6%88%BF&token=mike-api";
fetch(res_url)
.then(handleResponse)
.then(data => console.log(data))
.then(error => console.log(error))
function handleResponse(response) {
let contentType = response.headers.get('content-type')
if (contentType.includes('application/json')) {
return handleJSONResponse(response)
} else if (contentType.includes('text/html')) {
return handleTextResponse(response)
} else {
throw new Error(`Sorry, content-type ${contentType} not supported`)
}
}
function handleJSONResponse(response) {
return response.json()
.then(json => {
if (response.ok) {
return json
} else {
return Promise.reject(Object.assign({}, json, {
status: response.status,
statusText: response.statusText
}))
}
})
}
function handleTextResponse(response) {
return response.text()
.then(text => {
if (response.ok) {
return text
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText,
err: text
})
}
})
}