我是打字稿的新手
如何從我的回呼函式中讀取函式 json 回應?
這是我的功能,它回傳 html 內容...
async function getContent(src: string) {
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = { content: await response.text(), correlationId: response.headers.get("x-correlationid") };
return result;
} catch (error) {
if (error instanceof Error) {
return error.message;
} else {
return 'An unexpected error occurred';
}
}
}
這就是我試圖從回應中讀取 json 的方式。但是result.json ()以紅色高亮顯示錯誤“屬性 json 在型別字串上不存在”
getContent(src)
.then( result => result.json())
.then( post => {
iframe.contentDocument.write(post.content);
})
.catch( error => {
console.log(error);
});
***** 更新 ******
問題出在我的 getContent 函式內部,catch 塊必須以相同的物件結構回傳錯誤。
功能更新
async function getContent(src: string) {
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = { content: await response.text(), correlationId: response.headers.get('x-correlationid') };
return result;
} catch (error) {
if (error instanceof Error) {
return { content: error.message, correlationId: undefined };
} else {
return { content: 'An unexpected error occurred', correlationId: undefined };
}
}
}
和函式呼叫
getContent(src)
.then( result => {
iframe.contentDocument.write(result.content);
console.log(`I have the correlation ${result.correlationId}`);
})
.catch( error => {
console.log(error.content);
});
uj5u.com熱心網友回復:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#body
您可以在 fetch 方法回傳的回應物件上查看開箱即用的方法。您當前正在使用將text正文內容提取為文本的方法。您可能希望洗掉在回應中呼叫 json 的行,因為 iframe 檔案上的 write 方法無論如何只能使用字串:
getContent(src)
.then( post => {
iframe.contentDocument.write(post.content);
})
.catch( error => {
console.log(error);
});
簡而言之:getContent函式回傳的物件上不存在 .json 方法。您可以在內容上運行 JSON.parse,但正如我上面解釋的那樣,您應該將該json方法應用于您的回應。
uj5u.com熱心網友回復:
該json方法在response物件上可用。
在getContent您將content屬性設定為字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506920.html
標籤:javascript json 打字稿
