Access-Control-Allow-Origin Cors error

Hello!
I have a frontend that isn’t running on ICP. When I try to access canister functions from there using @dfinity/agent, I get this cors error.
Can anyone please enlighten me on how to resolve this?
I tried creating a .ic-assets.json file and defining headers there, but that hasn’t worked either.

Greatly appreciate any help.

Hello @cheersblock. Have you checked your network panel to inspect the request/response cycle that is leading up to this issue? In particular could you check the OPTIONS request that the browser is making to the /api endpoint and see if there is anything off with the response there?

This is where I am sending the request:

const fetch = require("node-fetch");
const pkgAgent = require("@dfinity/agent");
const { idlFactory: usersIdlFactory } = require("./users.did.js");
const { readFileSync } = require("fs");
const pkgPrincipal = require("@dfinity/principal");

const { HttpAgent, Actor } = pkgAgent;
const { Principal } = pkgPrincipal;

const getActor = async (_id, _host) => {

  const canisterId = Principal.fromText(_id);
  const host = _host; // Mainnet: 'https://ic0.app'

  const fetchOptions = {
    headers: {
      "Access-Control-Allow-Origin": "*",
    },
  };

  const agent = new HttpAgent({
    fetch: window.fetch.bind(window),
    host,
    fetchOptions,
  });

  // Local only
    await agent.fetchRootKey();

  return Actor.createActor(usersIdlFactory, {
    agent,
    canisterId,
  });
};


const getCanister = async (id, host) => {
  const actor = await getActor(id, host);
  return actor;
};
module.exports = { getCanister};

Its still not working

Check the network panel in the browser devtools to see what response you are getting from the local replica.

CORS issue

The response is not visible in your screenshot

Are you using Webpack?

Maybe you’re missing this config: sdk/webpack.config.js at master · dfinity/sdk · GitHub