Reputation: 920
A simple fetch in node js gives error TypeError: Cannot read property 'then' of undefined, I went through many answers here, everywhere it mentions to return the Promise, but in this case, the returned promise object is chained immediately with then(), below is the code.
const fetch = require("fetch").fetchUrl
fetch('http://example.com/movies.json').then((response) => {
console.log(response);
});
Upvotes: 0
Views: 2003
Reputation: 5202
Try the callback way:
const fetchUrl = require("fetch").fetchUrl
fetchUrl("http://kreata.ee/iso-8859-15.php", function(error, meta, body){
console.log(body.toString());
});
Upvotes: 1
Reputation: 11070
The fetch module does not use Promises, it uses traditional node-style callbacks. You can promisify the function using util.promisify:
const fetch = require("util").promisify(require("fetch").fetchUrl)
Note that this fetch module hasn't been updated for 4 years. I recommend using a more updated fetch module that supports promises like node-fetch, got, or request if you'd like to use promises.
Upvotes: 1
Reputation: 33
It look like fetch doesn't use promises, rather it uses callbacks.
So to do what you're looking to do you'd need to do this:
fetchUrl("http://example.com/movies.json", function(error, meta, body){
console.log(JSON.parse(body));
});
If you aren't using the package I linked let me know, but from what I can tell fetch doesn't use promises and this is the first thing I found on NPM.
Upvotes: 1