Search code examples
node.jsjsonserverclientsvelte

Calling Function from Nodejs at Client side: require is not defined


I understood that there are a few similar questions asking about this. However, I do not find a solution to my problem. I am using svelte and nodejs from my project. I am fetching JSON file from the server-side and wanted to call the function on the client-side using require. Below is my code on the server-side.

DataService.js

const fetch = require('node-fetch')

let data;
;(async ()=>{
    const res = await fetch('http://localhost:3000/api/tables.json');
    data = await res.json();
    // console.log(data);
})()

export const getTable = () => {
    console.log(data);
    return data;
    // console.log(data);
}

When I tried to call getTable() from the client-side, an error says "require is not defined".I understood from various answers that require is only for server-side and not client-side. Some solutions mentioned that I used consider using, Script, commonjs, browersify and more.

Here is my client-side code.

Catalog.svelte

<script >
import {getTable} from '../components/dataservice.js';

console.log(getTable()); //gives an error of require is not defined


</script>

<h1>Table</h1>

If I remove "const fetch = require('node-fetch')" from Dataservice.js, it gives me undefined and fetch is not defined.

Any help would be appreciated as I have struggled to resolve this for days.


Solution

  • This should work:

    const fetch = typeof window !== 'undefined'
      ? window.fetch
      : require('node-fetch');