【问题标题】:UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined [duplicate]UnhandledPromiseRejectionWarning:ReferenceError:未定义提取[重复]
【发布时间】:2021-11-26 03:29:37
【问题描述】:

我尝试使用 .then 响应和 .catch 但没有任何效果。运行测试脚本时出现以下错误。

我不想使用节点获取方法


const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'

         
            },
        });
        const json = await response.json();

谁能告诉我这里缺少什么?

(使用node --trace-warnings ... 显示警告的创建位置) (节点:12784)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。要在未处理的 Promise 拒绝时终止节点进程,请使用 CLI 标志 --unhandled-rejections=strict(拒绝 id:2) (节点:12784)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

【问题讨论】:

  • fetch 未内置在节点中。这是在浏览器中运行(如果是的话)还是在节点中?
  • 它在节点中运行。
  • 然后安装一个节点兼容的抓取包。

标签: javascript node.js


【解决方案1】:

fetch 不是 javascript,而是浏览器规范。参见例如here 获取详细信息。

唯一的解决方案是使用提到的节点包node-fetch或使用默认节点httplib。来自文档:

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
  host: 'www.random.org',
  path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been received, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been received, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();
                                                                                                        

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2020-11-15
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多