Cors Policy in React JS

Hello again,

I got cors policy when try send transaction using react js. It previously worked smoothly using standard js in index.html [using bsc testnet].

Here’s the code in index.html

async function contribute() {

    let user = Moralis.User.current();
  const walletAddress = user.get('ethAddress');
  const web3 = await Moralis.enableWeb3();
  const chainIdDec = await web3.eth.getChainId();       		
  
  if (chainIdDec == 97 ) {
  	const web3 = await Moralis.enableWeb3();
  	let stabcontract = new web3.eth.Contract(PresaleABI,PresaleContract);
  	
  	//input number from box contribute, dari 0.1 sampai 1
  	const tobuy = 0.1*1000000000000000000; // input 0.1 bnb, jadi 0.1 x 10^18 
  	var xbuy = new BigNumber(tobuy).toFixed();		

  	stabcontract.methods.buyToken(walletAddress
  			).send({
  				from: walletAddress,
  				value: xbuy
  			},function(err, res) {
  				if (err) {
  					console.log("An error occured", err);
  					return
  				}
  				console.log("Hash of the transaction: " + res)
  				})
  } else {
  	console.log("Connect to BSC Testnet Network!")
  }

}

Here’s the snapshot code in react:

const handleContribute = async () => {

try {
  const provider = new Web3.providers.HttpProvider(providerUrl);
  const web3 = new Web3(provider);
  const chainIdDec = await web3.eth.getChainId();
  const walletAddress = user.get("ethAddress");
  if(parseInt(inChainId) === parseInt(chainIdDec)){
    let stabcontract =  new web3.eth.Contract(PresaleABI, PresaleContract);
    const amountContribute = (countContribute * 1000000000000000000).toLocaleString('fullwide', { useGrouping: false });
    // const amountContribute = countContribute * 1000000000000000000;
    console.log(PresaleContract)
    console.log(amountContribute)
    
    stabcontract.methods.buyToken(walletAddress).send(
      {
        from: walletAddress,
        value: amountContribute,
      },
      function (err, res) {
        if (err) {
          console.log("An error occured", err);
          return;
        }
        console.log("Hash of the transaction: " + res);
      }
    );
  }else{
    console.log('beda')
  }

  // const amountContribute = (countContribute * 1000000000000000000).toLocaleString('fullwide', { useGrouping: false });
  // if(chainIdDec === inChainId){
  //   let stabcontract = new web3.eth.Contract(PresaleABI, PresaleContract);
  //   console.log(stabcontract)
  // }else{
  //   console.log('no')
  // }
} catch (error) {
  console.log(error.message)
}

}

Any idea why it responds differently between regular html and react?

Thanks alot!

I don’t know exactly why is failing, but you don’t have to use this in react, you can use enableWeb3 in react too

ah finally, thanks alot! i slipped on the sand.