Axios get giving undefined



关于axios get call,我遇到了一个奇怪的问题。

try {
console.log('assetAddress', assetAddress);
var options = {
method: 'GET',
url: `https://testnets-api.opensea.io/api/v1/events?only_opensea=false&limit=20&asset_contract_address=${assetAddress}`,
headers: { "Accept": 'application/json' }
};
console.log(options.url)
res = await axios.request(options);
return res.data;
} catch (e) {
//console.log(e)
}

当我在url中传递assetAddress,然后尝试获得结果,它显示未定义。但是当我硬编码的资产地址与我的实际0x15352F80426ec9b94412b45242d7040b5dFeB5E6。

为什么会这样,有线索吗?

似乎您的assetAddress变量的范围是这里的问题。

下面是使用两个不同版本

的两个例子

您可以在这里使用.then.catch函数而不是async / await

const assetAddress = "0x15352F80426ec9b94412b45242d7040b5dFeB5E6"
var options = {
method: 'GET',
url: `https://testnets-api.opensea.io/api/v1/events?only_opensea=false&limit=20&asset_contract_address=${assetAddress}`,
headers: {
"Accept": 'application/json'
}
};
axios.request(options)
.then(res => console.log(res.data))
.catch(error => console.log(error))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js"></script>


如果你还想使用经典版本,这里是版本。

const assetAddress = "0x15352F80426ec9b94412b45242d7040b5dFeB5E6"
async function loadData() {
console.log("Loading Data")
var options = {
method: 'GET',
url: `https://testnets-api.opensea.io/api/v1/events?only_opensea=false&limit=20&asset_contract_address=${assetAddress}`,
headers: {
"Accept": 'application/json'
}
};
try {
const res = await axios.request(options)
console.log(res)
} catch (error) {
console.log(error)
}
}
document.getElementById('loadDataButton').addEventListener('click', loadData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js"></script>
<button id="loadDataButton">Load data</button>

最新更新