Using HTTP Agent in a script

I’m trying to run a ts script with HTTP Agent like:

import { Actor, HttpAgent } from "@dfinity/agent";
const host = "http://localhost:8000/";
const agent = new HttpAgent({ host });

After I try ts-node script.ts, I get the error:

TypeError: Cannot read property 'bind' of undefined
    at getDefaultFetch 

You’ll need to bind global.fetch:

3 Likes

Oh, got it thanks! Dumb question, I’m getting an error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

How do I fix this?
My code is only:

import fetch from "node-fetch";
(global as any).fetch = fetch;

My tsconfig looks like:

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

I don’t know, but you may want to start by adopting the tsconfig used in GitHub - krpeacock/auth-client-demo: Example demo of how to use https://www.npmjs.com/package/@dfinity/auth-client to make authenticated calls to an IC app . Some of your entries are different.

Most probably you have a different node-fetch version, I am using "node-fetch": "^2.6.2" and the types
"@types/node-fetch": "^2.5.12"
this should work

Here’s a simpler working version inspired by @wang repo