Calling a server API in custom node's js

Hi,
I need to call a server API to POST some data in custom node's js file. I am trying to use "node-fetch" , but it always gives me " Cannot find module 'node-fetch'" I have installed the module. Module is available under "node_modules" folder.
I am using below line of code to test a simple server call:

const fetch = require('node-fetch');
fetch("some_url").then(res => console.log(res.text()))
.then(body => console.log(body));

Could you please suggest. Also is it a right way to do this?

Which folder contains the node_modules folder that contains node-fetch?

When posting code, please follow the forum instractions and wrap the code in back-ticks so that it is more readable thanks.

const fetch = require('node-fetch');
fetch("some_url").then(res => console.log(res.text()))
.then(body => console.log(body));

Where are you putting that code? If it is in a function node, you can't use require() because a function node uses a Node.js VM which prevents its use.

Instead you have to do the require in your node-red settings.js file assigning the output to the globals section. Then in your function you will have something like:

const fetch = global.get('fetch');
fetch("some_url").then(res => console.log(res.text()))
.then(body => console.log(body));

Where 'fetch' will be the name you assigned the require() to in settings.js.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.