【问题标题】:how to request API and send it to front如何请求 API 并将其发送到前台
【发布时间】: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

【问题讨论】:

    标签: javascript node.js rest express routes


    【解决方案1】:

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

    【讨论】:

    • 这是我做不到的
    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2021-11-22
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多