ReferenceError: fetch is not defined

前端 未结 10 1844
闹比i
闹比i 2020-11-29 17:48

I have this error when I compile my code in node.js, how can I fix it?

RefernceError: fetch is not defined

This is the function I am doing, it is re

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 18:22

    You can use cross-fetch from @lquixada

    Platform agnostic: browsers, node or react native

    Install

    npm install --save cross-fetch
    

    Usage

    With promises:

    import fetch from 'cross-fetch';
    // Or just: import 'cross-fetch/polyfill';
    
    fetch('//api.github.com/users/lquixada')
      .then(res => {
        if (res.status >= 400) {
          throw new Error("Bad response from server");
        }
        return res.json();
      })
      .then(user => {
        console.log(user);
      })
      .catch(err => {
        console.error(err);
      });
    

    With async/await:

    import fetch from 'cross-fetch';
    // Or just: import 'cross-fetch/polyfill';
    
    (async () => {
      try {
        const res = await fetch('//api.github.com/users/lquixada');
    
        if (res.status >= 400) {
          throw new Error("Bad response from server");
        }
    
        const user = await res.json();
    
        console.log(user);
      } catch (err) {
        console.error(err);
      }
    })();
    

提交回复
热议问题