使用axios与哈巴狗进行渲染

时间:2018-12-03 11:39:09

标签: node.js axios

我正在尝试在我的哈巴狗模板中显示使用axios进行的api调用的结果,但这似乎不起作用

// index.pug

extends layout

block content
  h1= 'Users List'
  p(id="users") Returned string: #{obj}

// allusers_controller

var axios = require('axios')

exports.DisplayData = function(req , res){

var obj;
var url = 'https://jsonplaceholder.typicode.com/todos/1'
axios.get(url).then(response => obj = response.id);
res.render('index.pug',{obj})
}

快速路由器

var express = require('express');
var router = express.Router();

//main controller
var userController = require('../controllers/allusers_controller');

/* GET home page. */
router.get('/', userController.DisplayData);

module.exports = router;

oBj不会被渲染。我想念什么?

1 个答案:

答案 0 :(得分:1)

您不太了解诺言如何工作,.then()是异步的,因此您的代码立即跳至res.render(),而objundefined ---您需要要做的就是将其更改为以下内容,以便在将响应放入res.render内之前不会调用.then()

var axios = require('axios')

exports.DisplayData = function(req , res){    
  var url = 'https://jsonplaceholder.typicode.com/todos/1'
  axios.get(url).then(response => {
    let obj = response.id;
    res.render('index.pug',{obj})
  }
}

此外,您也可以像这样使用async/await代替.then()

exports.DisplayData = async function(req , res){
  try{
    var url = 'https://jsonplaceholder.typicode.com/todos/1'
    let response = await axios.get(url);
    let obj = response.id;
    res.render('index.pug',{obj});
  }catch(e){
    res.render('error.pug');
  }
}