【问题标题】:Fetch data from Strava API and return data to table从 Strava API 获取数据并将数据返回到表中
【发布时间】: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&amp;redirect_uri=https://localhost:44370/strava/index&amp;response_type=code&amp;scope=activity:read_all" } 在本地主机上工作,但当 href 更改为 strava.com/oauth/… 时作为 Azure Wep 应用程序发布时不起作用。任何帮助非常感谢?

标签: javascript fetch-api strava


【解决方案1】:

res.json() 返回一个承诺,你需要使用.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));
}

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

【讨论】:

  • 感谢您迄今为止的帮助。我已经按照你上面所说的做了,然后尝试用结果填充一个 id=table 的表。我已将我尝试过的内容添加到我的原始问题中。非常感谢任何额外的帮助。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多