我无法从 Express API 的 fetch 中传输数据

问题描述 投票:0回答:1

我有一个问题,我不知道如何解决,它应该可以工作,但它不起作用

const getPhones = async () => {
  await fetch(url, requestOptions)
    .then((response) => response.text())
    .then((XMLdata) => {
      const parser = new XMLParser()
      const jObj = parser.parse(XMLdata)
      let data = jObj['soapenv:Envelope']['soapenv:Body']['ns:listPhoneResponse']['return']['phone']
      console.log(data)
      return data
    })
    .catch((error) => console.log('error', error))
}

函数返回这样的json,我可以在console.log(data)中看到它

[
  { name: 'SEP805E0C47A189', model: 'Third-party SIP Device (Basic)' },
  { name: 'SEPDCEB94CE9A65', model: 'Cisco 7821' },
  { name: 'TCT-442001', model: 'Cisco Dual Mode for iPhone' },
  { name: 'BOT-441015', model: 'Cisco Dual Mode for Android' },
  { name: 'SEP70708B219FC8', model: 'Cisco 8851' },
]

然后一切就和大家出口进口快递一样了

export const phonesData = (req, res) => {
  res.status(200).json(getPhones)
}

router.get('/api/phones', phonesData)

但是当我访问页面 http://localhost:3000/api/phones 时,我收到 200 响应,但我在控制台中看到的数据丢失了。我将console.log中的数据复制到一个常量中,并尝试替换export中的常量,数据出现了。 getPhones 函数是异步的,它等待 fetch 执行,然后将结果由 fast-xml-parser 解析为 json 返回。 我做错了什么?

api express asynchronous async-await fetch
1个回答
0
投票

getPhones
是一个 函数:

const getPhones = async () => {

在这里,您尝试返回函数本身,而不是调用它:

export const phonesData = (req, res) => {
  res.status(200).json(getPhones)
}

您可以通过添加括号调用(调用)函数。另请注意,

getPhones
是一个
async
函数,因此您需要
await
其结果:

export const phonesData = async (req, res) => {
  res.status(200).json(await getPhones());
}

或者,如果

async
版本的
phonesData
不适合您的需求,您可以使用
.then()
来跟踪结果:

export const phonesData = (req, res) => {
  getPhones().then(data => res.status(200).json(data));
}

无论哪种方式,您都需要调用该函数才能执行并返回其结果。

© www.soinside.com 2019 - 2024. All rights reserved.