从 Strava 获取数据 API 和 return 数据到 table

Fetch data from Strava API and return data to table

我已经尝试了很多事情并阅读了很多使用 Fetch 返回的数据作为对象放入 table 或类似对象的示例,但我似乎无法理解。以下代码授权 Strava 用户使用我的测试应用程序,然后获取用户最近 30 次活动。一旦数据作为 Promise 返回,我就可以在控制台中查看它,但不能使用它。我是个新手,所以只需要一些关于如何在 table.

中使用这些数据的指导

//我的代码如下


<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 函数进行了以下更改。然后我尝试用下面的代码填充 table 但没有运气

    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];
            }
        }
    }

res.json() returns一个promise,你需要用.then()得到结果,就像你在codeExchange()

function getActivities(res) {
  const activities_link = `https://www.strava.com/api/v3/athlete/activities?access_token=${res.access_token}`
  fetch(activities_link)
    .then((res) => res.json())
    .then(data => console.log(data));
}

如果您想从中填充 table,请调用执行此操作的函数来代替 console.log(data)

我找到了我一直在寻找的答案 - 工作代码包含在下面(这授权了 Strava 用户并用他们最近的 30 项活动填充了 table):

<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"

    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) => res.json())
            .then(data => populateTable(data));
    }

    function populateTable(data) {
        for (var i = 0; i < data.length; i++) {
            var table = "";

            for (var i in data) {
                table += "<tr>";
                table += "<td>"
                    + data[i].name + "</td>"
                    + "<td>" + data[i].distance + "</td>"
                    + "<td>" + data[i].average_heartrate + "</td>"
                    + "<td>" + data[i].moving_time + "</td>";
                table += "</tr>";
            
            }
            document.getElementById("table").innerHTML = table;
        }
    }

</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" />
    <nav class="navbar navbar-default">
    </nav>
    <div class="col-md-3"></div>
    <div class="col-md-6 well">
        <hr style="border-top:1px dotted #ccc;" />
        <div class="col-md-8">
            <table class="table table-bordered">
                <thead class="alert-info">
                    <tr>
                        <th>Activity Name</th>
                        <th>Distance</th>
                        <th>Heart Rate</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody id="table"></tbody>
            </table>
            </div>
        </div>