2

I am using the node-fetch module in node-express app and earlier I used to do import it in this way:

const fetch = require("node-fetch")

But now with te=he version "node-fetch": "^3.0.0", it does not allow me to use require, instead it suggests to use import as it is an ES module.

But the main problem I am facing is with the Headers in new version, it throws error fetch.Headers() is not a constructor, although I have been using it until last version. Following is my code:

const express = require('express');
const port = 8080;
const app = express();
const ejs = require('ejs');
const fetch = import("node-fetch");

app.use(express.json());

app.use(express.static(__dirname + "/public"));

app.get('/', (req, res) => {
    let myHeaders = new fetch.Headers();
    var uri = uri
    var options = {
        method: 'GET',
    };
    fetch(uri, options)
        .then(response => response.text())
        .then(result => {
            console.log(result);
            list = JSON.parse(result);
            res.render(__dirname + '/index.html');
        })
        .catch(error => console.log('error', error));
    
})

app.listen(port, () =>{
    console.log("Listening at 8080");
})

Error: TypeError: fetch.Headers is not a constructor

Nizar Kadri
  • 321
  • 2
  • 10
  • For me it was caused by next.js dynamic import not warning me that I didn't execute a yarn add node-fetch :-) – Zied Hamdi Sep 24 '21 at 15:31

1 Answers1

0

I hadnt's imported the node-fetch package, and since I was importing it dynamically on SSR rendering only (with next.js), I wasn't getting the error about the package not found

if( typeof window === 'undefined' ) {
    const Headers = (await import('node-fetch')).Headers
    headers = new Headers(headers)
}

That was the reason of the error for me

Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40