【问题标题】:Calling an api and return these values in Nodejs调用 api 并在 Nodejs 中返回这些值
【发布时间】:2020-08-24 23:52:03
【问题描述】:

我正在尝试建立一个小型网站。我使用 React 作为前端,Nodejs 作为后端,以及一些第三方 API。这里我的想法是,首先将表单数据发布到nodejs。从那时起,我接受节点中的数据并需要调用外部 api。为此,我正在使用 axios。从我的 api 接收值后,我必须将该值发送回响应应用程序。当我在邮递员中运行我的代码时,输​​出是 {}。我认为我没有从我的 api 中获取值,但不知道如何解决这个问题。我对这些技术很陌生。有人请帮我解决这个问题。提前谢谢你。这是我到目前为止所尝试的。

const express = require('express');
const axios = require('axios');
const router = express.Router();
const request = require('request');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended : false}));

router.get('/', (req, res) => {
    res.send(" Express Homepage is running...");
});

async function callApi(emailid, pswd) {
    return axios({
        method:'post',
        url:'http://51.X.X/api/login',
        data:  { 
            "email": `${emailid}`,
            "password": `${pswd}`
        },
        headers: {'Content-Type': 'application/json' }
    })};
    callApi().then(function(response){
        return response.data;
    })
    .catch(function(error){
        console.log(error);
    })

app.post('/api/login', (req, res) => {
   let emailid = String(req.body.email);
   let pswd = String(req.body.password);
  const data = callApi(emailid, pswd);
   if(data) {
    res.send(data);
   }else {
       res.json({msg : " Response data not recieved.."})
   }
  
});

【问题讨论】:

    标签: api express axios


    【解决方案1】:

    使用 async/await 语法来处理异步调用

    app.post('/api/login', async (req, res) => {
       let emailid = String(req.body.email);
       let pswd = String(req.body.password);
      const data = await callApi(emailid, pswd);
       if(data) {
        res.send(data);
       }else {
           res.json({msg : " Response data not recieved.."})
       }
      
    });
    

    【讨论】:

      【解决方案2】:

      问题是您没有等待异步调用完成。 使用官方文档中提到的 async-await https://www.npmjs.com/package/axios

      function callAPI(){
          const response = await axios({
             method:'post',
             url:'http://51.X.X/api/login',
             data:  { 
                "email": `${emailid}`,
                "password": `${pswd}`
             },
             headers: {'Content-Type': 'application/json' }
          })};
      
          return response
      }
      
      app.post('/api/login', async (req, res) => {
         let emailid = String(req.body.email);
         let pswd = String(req.body.password);
         //add try catch to catch exception
         const data = await callApi(emailid, pswd);
         if(data) {
             //check for response from axios in official doc and send what data you
             want to send
             res.send(data);
         }else {
            res.json({msg : " Response data not recieved.."})
         }
      });
      

      【讨论】:

      • 谢谢,很多 axios 发布请求确实返回了值,但我没有得到“const data”中的值以进一步使用它。我的响应是一个 js 对象。如何做到这一点..
      • axios 必须返回响应,你能告诉我你是如何实现的吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多