如何请求 API 并将其发送到前台

Posted

技术标签:

【中文标题】如何请求 API 并将其发送到前台【英文标题】:how to request API and send it to front 【发布时间】:2020-08-03 23:09:14 【问题描述】:

我是 node.js 的新手,我想练习一下。我找到了这个example。

我的主页很好home page 但是当我点击任何国家时我无法显示其信息,我的意思是我可以请求我点击的国家的数据但我无法将其发送到我的页面渲染以显示这些信息 我想要它看起来像这样 countryinfo

这是节点

    const express = require("express")
    const app = express()
    const https = require("https")
    var bodyParser = require('body-parser')
    app.set("view engine", "ejs")
    app.use(express.static("./public"))
    var urlencodedParser = bodyParser.urlencoded( extended: false )
    app.get("/" , (req, res) =>
        res.sendFile(__dirname + "/index.html")
    )

    app.get("/:thename" , (req, res) =>
        res.render("countryinfo")

    )
    app.post("/:thename" , urlencodedParser,(req, res) =>
        let theName = `https://restcountries.eu/rest/v2/name/$req.params.thename`;
        https.get(`https://restcountries.eu/rest/v2/name/$req.params.thename`, (resp) => 
        let data = '';

        // A chunk of data has been recieved.
        resp.on('data', (chunk) => 
          data += chunk;
        );

        // The whole response has been received. Print out the result.
        resp.on('end', () => 
          res.json(JSON.parse(data));
        );
     )
app.listen("3000")

这是javascript文件

countries.forEach(nation=>
    nation.addEventListener("click", getInfo)
    function getInfo () 
        var theName = nation.children[0].getAttribute("href")
        $.ajax(
            type: 'GET',
            url: theName,
            success: function()

            
        );
        $.ajax(
            type: 'POST',
            url: theName,
            data: name: theName,
            success: function(data)//updated data
            
        );
    
)

我应该怎么做才能将数据发送到呈现的页面? 这是我的目录的样子:directories

【问题讨论】:

【参考方案1】:

您可能希望在收到数据的成功函数中更新您的前端。

【讨论】:

这是我做不到的

以上是关于如何请求 API 并将其发送到前台的主要内容,如果未能解决你的问题,请参考以下文章