3 回答

TA貢獻1869條經驗 獲得超4個贊
你可以使用 .json() 方法:
const fetched = await fetch("/url", {
method: 'GET',
});
const fetchedJson: object = await fetched.json();
console.log(fetchedJson)

TA貢獻1966條經驗 獲得超4個贊
有幾種方法可以做到這一點。
使用承諾
獲取響應對象本身包含一些方法,可以幫助您獲得不同形式的響應,例如.json()、.text()和.status。點擊此處了解詳情。所以,如果你只是想將答案解析成一個 JSON 對象,你可以這樣做
function doSomethingOnParsedJson(res) {
// Do something on the response here...
}
function readOperacions() {
fetch("http://localhost:8080/operaciones", {
method: "GET",
})
.then(res => res.json())
.then(doSomethingOnParsedJson) // Pass in a function without parentheses
.catch(console.error);
}
如果你定義一個單獨的函數來執行你想對解析的響應做的工作并將函數(不帶括號)傳遞給它會更干凈,then但你也可以繼續并直接給它一個函數,如:
function readOperacions() {
fetch("http://localhost:8080/operaciones", {
method: "GET",
})
.then(res => res.json())
.then(parsedResponse => {
// do something...
})
.catch(console.error);
}
使用異步/等待
您還可以使用異步/等待功能來實現這一點。
function doSomethingOnParsedJson(res) {
// Do something on the response here...
}
async function readOperacions() {
try {
// Get the response from the server.
const res = await fetch("http://localhost:8080/operaciones", {
method: "GET",
});
// Parse it into a JSON object.
const parsedJson = res.json();
// Do something on it.
doSomethingOnParsedJson(parsedJson);
} catch (error) {
// Show an error if something unexpected happened.
}
}
邊注
在 Express 中有一種更簡潔的方法來發送 JSON 響應。您可以.json在 Express 響應對象上使用該方法。
app.get("/operaciones", async (req, res) => {
const rows = await readAll();
/* Don't do this!
res.setHeader("content-type", "application/json")
res.send(JSON.stringify(rows))
*/
/* Do this instead ;-) */
res.json(rows);
})
瞧!就這么簡單。

TA貢獻1752條經驗 獲得超4個贊
將 .then 添加到獲取鏈并打印結果:
fetch('http://example.com/movies.json')
.then(response => {
console.log('response: ' + JSON.stringify(response));
})
...
...
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
添加回答
舉報