【问题标题】:Showing API response on webpage在网页上显示 API 响应
【发布时间】:2020-05-16 16:37:20
【问题描述】:

我可以在我的节点控制台上以 json 格式 console.log() API 调用的响应,我怎样才能让它在我的网页上显示结果,并带有样式。

基本上在 app.post() 中,我在发出请求后创建了 console.log()。 我收到了回复,但我需要将其显示在我的网页上。

app.post("/",function(req,res){

            // INSTANTIATE A CLIENT
    let credentials= new CognitiveServicesCredentials('API-key-goes-here');
    let client=new WebSearchAPIClient(credentials);

            // MAKE REQUEST AND PRINT RESULT
    const query=req.body.item;
    client.web.search(query).then((result) => {
        let properties = ["images", "webPages", "news", "videos"];
        for (let i = 0; i < properties.length; i++) {
            if (result[properties[i]]) {
                // console.log(result);    // To see result types and all.
                // console.log(result[properties[i]]); // To see all tyes of results.
                // console.log(result.videos); // To display only the video results. 
                // res.send(result[properties[i]].value);
                // let url=(result[properties[i]].value);
                // console.log(url); // gives the same result.  

            } else {
                console.log(`No ${properties[i]} data`);
            }
        }
    }).catch((err) => {
        throw err;
    })
});

希望这会有所帮助。

【问题讨论】:

    标签: node.js api express


    【解决方案1】:

    在您的响应对象集类型中,JSON 解析和发送。

    res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ a: 1 }));

    【讨论】:

    • 你能看看它并告诉我该怎么做吗?
    • 设置header后可以直接传递对象
    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多