【问题标题】:How to fetch raw text from a url into node?如何从 url 中获取原始文本到节点中?
【发布时间】:2022-12-03 03:58:06
【问题描述】:

我正在尝试将 2022 Advent Of Code 中的数据提取到 Vscode 中,而无需将数百行原始数据复制并粘贴到我的 IDE 中。

let response = await fetch('https://adventofcode.com/2022/day/1/input')

let text = await response.text()

console.log(text)

这段代码在浏览器开发工具中运行完美,但是当我尝试在节点中运行它时,出现SyntaxError: await is only valid in async functions and the top level bodies of modules的错误

【问题讨论】:

  • 在异步函数中添加此代码

标签: node.js fetch


【解决方案1】:

await 关键字只能在 async 函数内使用。要修复您收到的错误,您可以将代码包装在 async 函数中,然后调用该函数,或者您可以在获取承诺上使用 .then() 方法来处理响应。

这是一个如何使用 async 函数的示例:

async function fetchData() {
  let response = await fetch('https://adventofcode.com/2022/day/1/input')
  let text = await response.text()
  console.log(text)
}

// Call the function to fetch the data
fetchData()

下面是使用 .then() 方法的示例:

fetch('https://adventofcode.com/2022/day/1/input')
  .then(response => response.text())
  .then(text => console.log(text))

这两种方法都应该允许您获取数据并将响应记录到控制台。

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 2019-11-18
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多