发送 axios 响应到渲染页面

sending axios response to render page

我正在使用 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 })
};

当我完全按照我希望的方式刷新 'record' 页面时,我在控制台(来自 console.log(album))收到了响应,但是我想在我的记录视图页面中使用此数据(使用哈巴狗)但我得到一个 "ReferenceError: album is not defined"

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

您可以将对 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,这让我看起来很不整洁。