从获取响应访问数据
accessing data from fetch response
当我 运行 此代码时,我得到以下响应
getText(priceUrl, options)
async function getText() {
let x = await fetch(priceUrl, options);
let y = x.text()
document.getElementById("demo").innerHTML = y;
//document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
console.log(y['nativePrice']['value'])
document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];
}
y 是这个回复
{"nativePrice":{"value":"0","decimals":18,"name":"Binance Coin","symbol":"BNB"},"usdPrice":0,"exchangeAddress":"0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73","exchangeName":"PancakeSwap v2"}
现在,当我尝试访问这些值以在我的前端使用它们时
//document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
console.log(y['nativePrice']['value'])
document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];
我明白了
Uncaught (in promise) TypeError: y.nativePrice is undefined
我无法访问这些值,如果我使用 x.json() 我只能取回 promis 对象
我知道有几个关于获取的问题很安静,但我仍然无法弄清楚如何从我的响应中访问值
您可以等待,直到承诺得到解决。喜欢y = await x.json()
您可能会发现这也有帮助...
The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON. Source
当我 运行 此代码时,我得到以下响应
getText(priceUrl, options)
async function getText() {
let x = await fetch(priceUrl, options);
let y = x.text()
document.getElementById("demo").innerHTML = y;
//document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
console.log(y['nativePrice']['value'])
document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];
}
y 是这个回复
{"nativePrice":{"value":"0","decimals":18,"name":"Binance Coin","symbol":"BNB"},"usdPrice":0,"exchangeAddress":"0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73","exchangeName":"PancakeSwap v2"}
现在,当我尝试访问这些值以在我的前端使用它们时
//document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
console.log(y['nativePrice']['value'])
document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];
我明白了
Uncaught (in promise) TypeError: y.nativePrice is undefined
我无法访问这些值,如果我使用 x.json() 我只能取回 promis 对象
我知道有几个关于获取的问题很安静,但我仍然无法弄清楚如何从我的响应中访问值
您可以等待,直到承诺得到解决。喜欢y = await x.json()
您可能会发现这也有帮助...
The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON. Source