【问题标题】:fetch not recognized as an async functionfetch 未被识别为异步函数
【发布时间】:2021-01-09 01:17:37
【问题描述】:

当我在 devtools 的控制台中编写此代码时:

const response = await fetch("http://localhost:5001/api/products", {
    headers: {"Content-Type":"application/json"}
});
const products = await response.json();

我能够成功获取数据。

但是当我在 JS 文件中使用相同的代码运行我的节点项目时,我收到以下错误:

Uncaught SyntaxError: Unexpected reserved word

【问题讨论】:

  • 您使用的是什么版本的节点? (你可以通过node --version找到这个)
  • 你安装了node-fetch吗?
  • v12.18.1。尝试了@3limin4t0r 的建议,但没有成功。
  • @ciaodejan 安装后你需要这个库吗?如果你不这样做,你仍然不能使用fetch。确保您拥有const fetch = require('node-fetch'),如Loading and configuring the module中所述
  • 不是fetch没有被识别,是await关键字。

标签: javascript node.js async-await fetch


【解决方案1】:

await 不能在 async 函数之外使用,除非您在 Node 14.3.0+ 上并使用 ESM。将代码包装在像(async () => { /* your code here /* })(); 这样的块中,你应该很高兴。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多