将Express与axios结合使用可从数据库进行api调用

时间:2019-07-14 18:54:17

标签: javascript express axios

我正在建立一个项目,其中api密钥存储在数据库中。我需要不刷新即可进行api调用(我正在尝试在页面加载时执行此操作),因此我决定使用Axios,以便为该帐户填充数据。

使用Axios时我什么也不返回,但是如果我执行相同的路由并调用该路由,它将返回数据。

//逻辑说明

我必须查询数据库以获取用户密钥。因此,我做了一条明确的途径,即查询数据库返回键,然后使api对象再调用具有回调的api方法。

因此,我使用Axios调用了该路由,因此它将按照我上面的说明进行操作。但是,即使api方法有回调,数据也永远不会返回到axios对象。

//Load The Page View

router.get('/api',(req,res,next)=>{

  res.render('apiView');
})


//The Route for the API I tried POST and GET with no success This Is Called by Axios

router.get('/api/account',(req,res,next)=>{

  User.findById(req.user._id).then(UserObj=> {

    let MyApiObj = new Api(UserObj.key,UserObj.Secret);

    return MyApiObj.methodForApi()

  }).catch((err)=>{

    console.log(err)
  })

})


//Axios in the JS FILE So above is what Axios is calling when I click the button I am trying to do this on page load so its called automatically. I have the button for testing purpose.


document.getElementById('button').onclick = ()=>{

  axios.get('http://localhost:4000/api/account')
  .then((result)=>{

    console.log(result)

    document.getElementById('accountInfo').innerText = result.Name;

  })
  .catch((err)=>{
    console.log(err);
  })
}

0 个答案:

没有答案