【发布时间】:2022-01-24 20:59:10
【问题描述】:
我已经尝试了很多事情,并阅读了很多使用 Fetch 返回的数据作为对象放入表或类似对象的示例,但我似乎无法理解。以下代码授权 Strava 用户使用我的测试应用程序,然后获取用户最近 30 次活动。一旦数据作为 Promise 返回,我可以在控制台中查看它,但不能使用它。我是个新手,所以只需要一些关于如何在表格中使用这些数据的指导。
//我的代码在下面
<script>
//reAuthorize Click
function Authorize() {
document.location.href = "https://www.strava.com/oauth/authorize?client_id=XXX&redirect_uri=https://localhost:44370/strava/index&response_type=code&scope=activity:read_all"
}
const codeExchangeLink = `https://www.strava.com/api/v3/oauth/token`
function codeExchange() {
fetch(codeExchangeLink, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: '@ViewBag.cId',
client_secret: '@ViewBag.cSec',
code: '@ViewBag.code',
//need to do this to get a new refresh token that 'reads all' and issues a new Access Token - refer to comments below
grant_type: 'authorization_code'
})
})
.then(res => res.json())
.then(res => getActivities(res))
}
// getActivities
const auth_link = "https://www.strava.com/oauth/token"
function getActivities(res) {
var obj;
const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
fetch(activities_link)
.then((res) => console.log(res.json()))
}
</script>
<form asp-action="Index" method="get">
<input type="text" id="cId" value="@ViewBag.cId" />
<input type="text" id="cSec" value="@ViewBag.cSec" />
<input type="text" id="rT" value="@ViewBag.rT" />
<input type="text" id="code" value="@ViewBag.code" />
<input type="text" id="test" />
</form>
<input type="button" onclick="Authorize()" value="ReAuthorise" />
<input type="button" onclick="codeExchange()" value="Get Activities" />
// 在@Barmar 的帮助下,我对 getActivities 函数进行了以下更改。然后我尝试用以下代码填充表格,但没有成功
async function getActivities(res) {
const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
await fetch(activities_link)
/* .then((res) => console.log(res.json()))*/
.then((res) => res.json())
.then(data => populateTable(data));
}
function populateTable(data) {
for (var i = 0; i < data.length; i++) {
// create a new row
var newRow = table.insertRow(data.length);
for (var j = 0; j < data[i].length; j++) {
// create a new cell
var cell = newRow.insertCell(j);
// add value to the cell
cell.innerHTML = data[i][j];
}
}
}
【问题讨论】:
-
您需要在
getActivities()中使用res.json(),就像在codeExchange()中使用它一样。您需要另一个.then()才能使用结果。 -
您怎么知道在一个函数中执行此操作的正确方法,而在另一个函数中却不知道?
-
@Barmar 我正在从我还不完全理解的示例中学习。我的 Javascript 知识有限
-
@Barmar 如果您能提供一个示例,说明如何将数据返回到对象或变量中,然后填充表格,我将不胜感激?对我缺乏理解表示歉意
-
嗨@Barmar,我还有另一个问题,你可以帮忙解决。我的原始问题顶部的代码:
function Authorize() { document.location.href = "https://www.strava.com/oauth/authorize?client_id=XXX&redirect_uri=https://localhost:44370/strava/index&response_type=code&scope=activity:read_all" }在本地主机上工作,但当 href 更改为 strava.com/oauth/… 时作为 Azure Wep 应用程序发布时不起作用。任何帮助非常感谢?
标签: javascript fetch-api strava