Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

使用nodejs,通过async与await加axios请求第三方外部接口,无法同步获取数据,各位大佬有什么解决方案吗?

以下是我的代码

image.png
image.png
const express = require('express')
const axios =require('axios');
const { response } = require('express');
const app = express()
const port = 3000

app.get('/', (req, res) => {

// 代表获取请求参数
console.log(req.url);
console.log('req.method',req.method);
let robortText='';
getRobort().then(function(res){
  robortText=res;
})
console.log('robortText的数据为:',robortText);
res.send(robortText)

});
app.all("*",function(req,res,next){

//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
// if (req.method.toLowerCase() == 'options')
//   res.send(200);  //让options尝试请求快速结束
// else
//   next();

});
//获取第三方api数据
let str=encodeURI('你好');
function robotData(){

  return new Promise((resolve,reject)=>{
    axios.get("http://api.qingyunke.com/api.php?key=free&appid=0&msg="+str)
      .then(function (response) {
        resolve(response);
      })
      .catch(function (error) {
        reject(error);
      });
  })

}
async function getRobort(){

robortText=await robotData();
console.log(robortText.data.content);
return robortText.data.content;

}

app.listen(port, () => console.log(Example app listening on port ${port}!))

运行情况

image.png

页面并没有数据,因为robortText并没有同步获取到数据

image.png
求大佬帮忙!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

楼上正答,你 res.send 了一个寂寞

getRobort().then(res => {
    res.send(res);
})

// 或者

app.get('/', async (req, res) => {

  // ...
  let rebortText = await getRobort();
  
  res.send(rebortText)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...