我正在试着建立一个小网站。因为我使用React作为前端,Nodejs作为后端,以及一些第三方api。这里我的想法是,首先将表单数据发布到nodejs。然后,我接受节点中的数据,并需要调用外部api。为此,我使用了axios。从我的api收到值后,我必须将该值发送回react应用程序。当我在postman中运行代码时,输出为{}。我认为我没有从我的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.."})
}
});发布于 2020-08-24 21:23:55
使用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.."})
}
});发布于 2020-08-24 23:52:04
问题是你没有等待异步调用结束。按照官方文档https://www.npmjs.com/package/axios中所述使用async-await
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.."})
}
});https://stackoverflow.com/questions/63559658
复制相似问题