Request are blocked by CORS policy: No 'Access-Control-Allow-Origin'

I have a number of cloud function calls i.e. quoteDex and swapDex. I can call quoteDex without any problems. The moment I call swapDex I get the following error:

Access to XMLHttpRequest at 'https://eipszcn4otr3.moralis.io:2053/server/functions/swapDex' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As you can see from image above:
call to quoteDex - success
call to swapDex - fails
call to quoteDex - success

This call has worked previously (tested few days ago). It has stopped working. Please advise…

Checking thanks for reporting

1 Like

You probably have some syntax error inside that function. Do you mind posting that cloud function here?

const web3 = Moralis.web3ByChain("0x1"); // mainnet

Moralis.Cloud.define("swapDex", async (request) => {

  const logger = Moralis.Cloud.getLogger();

  const network = request.params.network;

  const fromAddress = request.params.fromAddress;

  const fromToken = request.params.from;

  const toToken = request.params.to;

  const amount = request.params.amount;

  const slippage = request.params.slippage;

  const referrerAddress = "**REDACTED**";

  const fee = 3;

  const networkChainId = network == "ethereum" ? 1 : 56;

  const url = `https://api.1inch.exchange/v3.0/${networkChainId}/swap?fromAddress=${fromAddress}&fromTokenAddress=${fromToken}&toTokenAddress=${toToken}&amount=${amount}&slippage=${slippage}&fee=${fee}&referrerAddress=${referrerAddress}`;

  logger.info(`1inch Swap: ${url}`);

  const response = await Moralis.Cloud.httpRequest({

    url: url,

    headers: {

      "Content-Type": "application/json;charset=utf-8",

    },

  });

  const EthTransactions = Parse.Object.extend("EthTransactions");

  const query = new Parse.Query(EthTransactions);

  query.equalTo("from_address", fromAddress);

  query.descending("createdAt");

  const resultQuery = await query.first();

  let gasPrice = parseInt(response.data.tx["gasPrice"]);

  console.log(gasPrice);

  gasPrice = "0x" + gasPrice.toString(16);

  const result = {

    data: response.data.tx["data"],

    to: response.data.tx["to"],

    value: `0x${response.data.tx["value"]}`,

    //gasPrice: `0x${parseInt(response.data.tx["gasPrice"])}`,

    //gas: web3.utils.toHex(response.data.tx["gas"]),

    from: response.data.tx["from"],

    nonce: web3.utils.toHex(resultQuery.attributes.nonce + 1),

  };

  return result;

});

P.S I have redacted my referrer address

If you change console.log(gasPrice); to logger.log(gasPrice);, do you see it in your logs?
I am thinking you could check so that response is not undefined.
Same goes with resultQuery… Check so that it is not undefined.
Let me know if the issure persists after these checks

1 Like

The above has worked. Thank you

1 Like