Ad

TypeError: Cannot Read Property 'then' Of Undefined - Trying To Fetch Data In Pure Javascript

- 1 answer

I'm trying to fetch data using pure javascript from a socket endpoint with socket.io. The idea is to use a socket server between the clients and my API in localhost for now.

I wanted to use nodejs fetch before, but the fetch function was not recognized, then I uncluded require("fetch").fetchUrl doing "npm install fetch" before.

const fetch = require("fetch").fetchUrl
const io = require('socket.io')();

fetch('http://localhost/')    
.then(response => response.json()) 
.then(responseJson=>console.log(responseJson))

const port = 3001
io.listen(port)
console.log('Server available at: http://localhost:', port)

TypeError: Cannot read property 'then' of undefined

Ad

Answer

The post was corrected following @Bhawana's answer: use const fetch = require("fetch"); only instead of const fetch = require("fetch").fetchUrl or you can go with node-fetch package.

The solution for this problem was very simple: replacing const fetch = require("fetch") by const fetch = require('node-fetch')

Ad
source: stackoverflow.com
Ad