繁体   English   中英

如何从 api 获取数据并将其插入新的 JSON object

[英]How to Fetch data from api and insert it inside a new JSON object

我正在尝试从现有的 api 端点获取数据,并使用该数据的一部分使用 nodejs 和 express 创建一个新端点,在这种情况下,我试图从https://jsonplaceholder.typicode.com/posts/ 1并将其插入我的新 object。 我对此比较陌生,看来我在解决这个问题的方法中遗漏了一些东西。 我希望有人能指出我正确的方向。 以下是我想要的结果

{
"userId": "1",
"another": "yam",
"isLearning": true,
"level": "apprentice"
}

到目前为止,以下是我的代码:

app.get('/contacts', (req, res) => {
    const fetch = require('node-fetch');



    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(jsonData => jsonData.json())
        .then(data => printInfo(data))

    let printInfo = (data) => {
        
        console.log(data.userId)
    }

    const user = {
        userId: data.userId,
        another: "yam",
        isLearning: true, 
        level: 'apprentice'
    };
    return res.json(user);
})
const fetch = require('node-fetch');

app.get('/contacts', (req, res) => {

    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(data=> data.json())
        .then(data => {
            const user = {
                userId: data.userId,
                another: "yam",
                isLearning: true, 
                level: 'apprentice'
            };
            return res.json(user);
        })
})

这种方法会更优雅。 我们使用 fetch 从 API 端点获取数据。 然后它使用.then()方法将数据解析为 JSON 格式并将其存储在变量data中。 最后,它使用来自 API 端点的数据创建一个新的 object,并将其作为 JSON 数据返回。

Edit: As pointed out by @danh, this works the formation of the user object must happen after the api request completes (because it depends on data from the request).In the OP code, the formation of the object is attempted before the API完成,即使代码“稍后”出现在源代码中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM