簡體   English   中英

Node.js API 需要點擊獲取 JSON 數據

[英]Node.js API needs to click to fetch JSON data

我正在嘗試使用笑話 API 和休息國家 API。 我制作了 2 個異步函數,但是當我使用國家/地區 API 時,我需要在加載國旗和國徽圖像之前兩次單擊提交按鈕。 笑話 api 立即檢索數據。

app.post("/", urlEncodedParser, (req, res) => {
    sendJokeRequest();
    let countryName = req.body.country;
    console.log(countryName);
    sendCountryRequest(countryName);
    res.render("api-page", {
        data: req.body.country,
        joke: joke,
        countryFlag: countryFlag,
        countryCoatOfArms: countryCoatOfArms
    });         
});
var joke;
var countryFlag, countryCoatOfArms

const sendJokeRequest = async () => {
    try {
        const response = await axios.get("https://api.chucknorris.io/jokes/random");
        console.log(response.data.value)
        joke = response.data.value;
    
    } catch (err) {
        console.error(err);
    }
};
const sendCountryRequest = async (country) => {
    try {
        const response = await axios.get(`https://restcountries.com/v3.1/name/${country}?fullText=true`);
        console.log(response.data[0]);
        countryFlag = response.data[0].flags.svg;
        countryCoatOfArms = response.data[0].coatOfArms.svg;
    
    } catch(err) {
        console.error(err);
    }
}

因為sendJokeRequestsendCountryRequestasync的, countryFlag sendCountryRequest sendJokeRequest joke res.render(... countryCoatOfArms

這應該工作

app.post("/", urlEncodedParser, async (req, res) => {
    try {
        const joke = await sendJokeRequest();
        const countryName = req.body.country;
        console.log(countryName);
        const {countryFlag, countryCoatOfArms} = await sendCountryRequest(countryName);
        res.render("api-page", {
            data: req.body.country,
            joke,
            countryFlag,
            countryCoatOfArms
        });
    } catch(err) {
        // handle errors here in one place
    }
});

const sendJokeRequest = async() => {
    const response = await axios.get("https://api.chucknorris.io/jokes/random");
    console.log(response.data.value)
    return response.data.value;
};

const sendCountryRequest = async(country) => {
    const response = await axios.get(`https://restcountries.com/v3.1/name/${country}?fullText=true`);
    console.log(response.data[0]);
    countryFlag = response.data[0].flags.svg;
    countryCoatOfArms = response.data[0].coatOfArms.svg;
    return {countryFlag, countryCoatOfArms};
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM