首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >调用api并在Nodejs中返回这些值

调用api并在Nodejs中返回这些值
EN

Stack Overflow用户
提问于 2020-08-24 18:56:30
回答 2查看 66关注 0票数 0

我正在试着建立一个小网站。因为我使用React作为前端,Nodejs作为后端,以及一些第三方api。这里我的想法是,首先将表单数据发布到nodejs。然后,我接受节点中的数据,并需要调用外部api。为此,我使用了axios。从我的api收到值后,我必须将该值发送回react应用程序。当我在postman中运行代码时,输出为{}。我认为我没有从我的api中获得值,但我不知道如何解决这个问题。我对这些技术还是个新手。有人能帮我解决这个问题吗?提前谢谢你。这是我到目前为止尝试过的东西。

代码语言:javascript
运行
复制
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.."})
   }
  
});
EN

回答 2

Stack Overflow用户

发布于 2020-08-24 21:23:55

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

代码语言:javascript
运行
复制
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.."})
   }
  
});
票数 0
EN

Stack Overflow用户

发布于 2020-08-24 23:52:04

问题是你没有等待异步调用结束。按照官方文档https://www.npmjs.com/package/axios中所述使用async-await

代码语言:javascript
运行
复制
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.."})
   }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63559658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档