【问题标题】:sending axios response to render page向渲染页面发送 axios 响应
【发布时间】:2018-03-24 20:30:13
【问题描述】:

我正在使用 axios 从外部 api 请求数据,我希望在我的渲染页面中使用响应,我的代码如下:

//This is from my controller which is required in my main routes
exports.recordBySlug = async (req, res, next) => {
    const record = await Record.findOne({ slug: req.params.slug });
    if(!record) return next();

    const url = API_URL

    axios
        .get(url)
        .then(res => {
            const album = res.data.album;
            console.log(album)
        })
        .catch(console.error);

    res.render('record', { album })
};

当我完全按照我的希望刷新“记录”页面时,我在控制台中收到了响应(来自console.log(album)),但是我想在我的记录视图页面中使用这些数据(使用哈巴狗)但我得到了一个“ReferenceError:专辑未定义”

我想我可能需要使用 await 但不确定我做得对。我希望我接近解决方案!

【问题讨论】:

    标签: javascript node.js express pug axios


    【解决方案1】:

    您可以将对 render 的调用移动到回调内部:

    axios
        .get(url)
        .then(res => {
            const album = res.data.album;
            console.log(album);
            res.render('record', { album })
        })
        .catch(next);
    

    如果你想使用await 来隐藏 Promise,它会是这样的:

    try {
        const res = await axios.get(url);
        const album = res.data.album;
    
        console.log(album);
        res.render('record', { album });
    }
    catch (err) {
        next(err);
    }
    

    不确定是否有办法摆脱try/catch,这让我觉得它看起来不整洁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 2017-09-28
      • 1970-01-01
      • 2020-03-25
      • 2014-05-27
      • 2019-01-27
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多