Has been blocked by CORS policy

hello,

I was trying to connect moralis but got no success, was working fine till yesterday.

Now i am getting this :

Access to XMLHttpRequest at ‘https://mj5grpndps10.moralis.io:2053/server/functions/getItems’ from origin ‘http://localhost:8000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Uncaught (in promise) Error: XMLHttpRequest failed: “Unable to connect to the Parse API”
at handleError (moralis.js:21781)

server V. - 0.0.197

didn’t update server to 0.205 because this update has some problems like invalid getUserItems function’, that already defined and working in old version.

please help me to fix this issue.

thanks

Please double-check our common issues at FAQ - Common Issues & How To Get Help as well as how to properly submit if nothing there helped you.

  • Provide any screenshot about your error.
  • Provide the code properly following this guide: FAQ - How to post code in the forum
  • Step by step on how to replicate the issue.
  • Provide your subdomain.

you can’t update the server version? If there is an error somewhere in your cloud functions that’s preventing you from updating what you can do is:

  1. Copy all your cloud functions to a text editor
  2. Delete all cloud function definitions from your Moralis Server Instance and press “Save”
  3. You should now be able to update to the latest server version

CORS errors are often related to Cloud Function errors

Unable to connect to Parse API is often a problem with not initializing the Moralis SDK properly with server url and app ID.

1 Like

UPDATE:
After deleting the server and spinning up a new one, it works again. But I notice that it takes quite a long time for the server to save the userInfo and then reply with “Success”. Is there anything I can do from my side to optimize?

problemDescription

Also facing the CORS and API error:
AccesXMLHttpRequestDenied
Although Setup is the same as three hours ago (API and SERVER_URL), just took a lunch break and now the error pops up. The only thing that changed is that I restarted Ganache GUI, So I try to connect with a different account, but this shouldn’t cause any issues, right?

ErrorMessage
Error: XMLHttpRequest failed: "Unable to connect to the Parse API"
    at handleError (moralis.js:21781)
main.js
Moralis.initialize("au8ghcOjDuBu3zaR4eDQzuBXJOBo7OwMfMXnEGZ7");
Moralis.serverURL = 'https://tghknes7imhf.moralis.io:2053/server'

init = async () => {
    hideElement(userInfo);
    hideElement(createItemForm);
    window.web3 = await Moralis.Web3.enable();
    initUser();
}

initUser = async () => {
    if(await Moralis.User.current()){
        hideElement(userConnectButton);
        showElement(userProfileButton);
        showElement(openCreateItemButton);
    }else{
        showElement(userConnectButton); 
        hideElement(userProfileButton);
        hideElement(openCreateItemButton);
    }
}

login = async () => {
    try{
        await Moralis.Web3.authenticate();
        location.reload();
    } catch (error){
        console.log(error);
    }
}

logout = async () => {
    await Moralis.User.logOut();
    hideElement(userInfo);
    initUser();
}

openUserInfo = async () => {
    user = await Moralis.User.current();
    if (user){
        const email = user.get('email');
        if(email){
            userEmailField.value = email;
        } else {
            userEmailField.value = "";
        }

        userUsernameField.value = user.get('username');

        const userAvatar = user.get('avatar');
        if(userAvatar){
            userAvatarImg.src = userAvatar.url();
            showElement(userAvatarImg);
        } else {
            hideElement(userAvatarImg);
        }

        showElement(userInfo);
    } else {
        login();
    }
}

saveUserInfo = async () => {
    user.set('email', userEmailField.value);
    user.set('username', userUsernameField.value);

    if (userAvatarFile.files.length > 0) {
        const avatar = new Moralis.File("avatar.jpg", userAvatarFile.files[0]);
        user.set('avatar', avatar);
      }
    
    await user.save();
    alert("User Info saved successfully");
    openUserInfo();
}

hideElement = (element) => element.style.display = 'none';
showElement = (element) => element.style.display = 'block';

const userConnectButton = document.getElementById("btnConnect");
userConnectButton.onclick = login;
const userProfileButton = document.getElementById("btnProfileInfo");
userProfileButton.onclick = openUserInfo;

const userInfo = document.getElementById("userInfo");
const userUsernameField = document.getElementById("textUsername");
const userEmailField = document.getElementById("textEmail");
const userAvatarImg = document.getElementById("imgAvatar");
const userAvatarFile = document.getElementById("fileAvatar");

document.getElementById("btnCloseUserInfo").onclick = () => hideElement(userInfo);
document.getElementById("btnLogout").onclick = logout;
document.getElementById("btnSaveUserInfo").onclick = saveUserInfo;

const createItemForm = document.getElementById("createItem");

const createItemNameField = document.getElementById("textCreateItemName");
const createItemDescriptionField = document.getElementById("textCreateItemDescription");
const createItemPriceField = document.getElementById("numberCreateItemPrice");
const createItemStatusField = document.getElementById("selectCreateItemStatus");
const createItemFile = document.getElementById("fileCreateItemFile");

const openCreateItemButton = document.getElementById("btnOpenCreateItem");
openCreateItemButton.onclick = () => showElement(createItemForm);
document.getElementById("btnCloseCreateItem").onclick = () => hideElement(createItemForm);

init();
1 Like

What do you mean by

The only thing that changed is that I restarted Ganache GUI

Was this a “quick start” where it creates a brand new local blockchain? or just closing ganache and loading the same workspace again? There is a difference in that “all of a sudden” the current block number and nonce is different and this can mess up the sync state.

Try manually restarting the Moralis server instance by pressing the “Update / Restart” button.

1 Like

It was a quick start. Thank you @mayjer for making this clear. Will use the same workspace from now on.
I also found this article that sheds light on the CORS ‘same origin policy’ error.I leave it here for future readers.

Note:
I just cleaned up my setup, will only use same ganache workspace and local server port for this server.
First got this when saving UserInfo:

Access to XMLHttpRequest at 'https://lwg4jsnzwdtr.moralis.io:2053/server/classes/_User/FVMAzuM0a5'
 from origin 'http://localhost:8000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
It does not have HTTP ok status.

As well as

moralis.js:21641 POST https://lwg4jsnzwdtr.moralis.io:2053/server/classes/_User/FVMAzuM0a5 net::ERR_FAILED

Then, after 30 seconds of banging my head against an imaginary wall:

USER INFO SAVED SUCCESSFULLY

without any further action on my side, as I was banging my head as already described, haha.

So, I don’t know if this helps you in anyway of improving on the server side or not, as I am, and I am sure you can tell, pretty new to the space. I can only guess at this point where the problem comes/came from. Maybe the newly spun up server was still initializing some things in the back, although I already could connect FRPC to.

Hm,
Any way, Great Service and AWESOME SUPPORT! thank you guys!

1 Like

I have the same issue as you too. So your fix is just to wait 30 secs? Don’t think this should be the correct way of doing tho.

Hi @TheStars,
I am sorry, maybe my post from above was not as clear as could be. I think that spinning up a new server fixed the problem. It was after 30 seconds that suddenly the function call worked and does ever since. Did you try spinning up a new server? Can you share some more details about your setup?

I’ll be making a more detailed post later but I don’t think setting up a new server will fix this problem as this issue my pop up again after awhile. I don’t have this issue when I first create the server and only realized that I have this issue a few days later.

I’m currently using the latest version of Next.js with Truffle set up.

You were right. I had to spin up a new server to fix it. Probably due to the server being to old and causing issues with CORs

3 Likes

I’ve had this error message a few times. After reading all the posts and trying everything, and it usually ended up being the result of trying to console.log something that was not yet ready or some other type error.

But now I have it again

Access to fetch at 'https://speedy-nodes-nyc.moralis.io/xxxxxxxxxxxxxxxxxx/eth/goerli' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This time it is happening when I’m trying to send a transaction from a signer attached to an rpcProvider using the moralis speedy nodes, using ethers.js. I’m trying to send ether to accounts NOT using Metamask but with new accounts created in the app. There are some demo apps that do this using Web3.js but Ethers.js treats the signers differently and maybe I’m doing something wrong.

This is right around where the error happens, in a catch block of this:


      tx = {
        gasLimit: gasLimit,
        gasPrice: gasPrice,
        to: tempWallet.address,
        value: value,
      };
    }

    signer
      .sendUncheckedTransaction(tx)
      .then((txObj) => {
        txObj.wait();
        console.log("txHash", txObj.hash);

This is the response.

Error: missing response (requestBody="{\"method\":\"eth_sendTransaction\",\"params\":[{\"gas\":\"0x5208\",\"gasPrice\":\"0x54f4dc53\",\"value\":\"0x372458e8d0768\",\"from\":\"0xxxxxxxxxxxxxxxxxxxxxxxxxx\",\"to\":\"0x78ffb95017388d09fdfa7e6856bbbbba8de5e55e\"}],\"id\":47,\"jsonrpc\":\"2.0\"}", requestMethod="POST", serverError={}, url="https://speedy-nodes-nyc.moralis.io/xxxxxxxxxxxxxxxxx/eth/goerli", code=SERVER_ERROR, version=web/5.6.0)

Any idea? I’m really confused by the whole CORS error that keeps popping up in surprising places and is really hard to track down.

Id you look in network tab in the browser, for that request, do you see more info? Or only a CORS error?

A CORS error can also happen when the url is blocked, or when it gives timeout.

Yes, both the mumbai and goerli speedy nodes are being blocked when I try to do a send transaction from the rpcProvider.

Everything works with Moralis when I use the web3Enabled, but the whole point of my app is to be able to send and receive without Metamask, like in Safari or in a mobile browser.

I authenticated using the magic.link integration thinking that the Moralis.transfer would still work, but it throws an error expecting web3Enabled. I have been using ethers.js and rpcProvider transactions. Everything works for reading but when I try to send from the authenticated signer=true account the Moralis speedynode blocks me.

I think it’s because Moralis is not doing key management for the speedy nodes even if you are trying to transfer from an isAuthenticated account. I tried replacing the Moralis nodes with Alchemy, and I got a more specific error message about key management. Then I tried it again with the Magic.Link providers and it worked. So I guess I can’t use the Moralis nodes for my project…

How would one go about using Moralis to make a dapp that works without Metamask installed, like on Safari? Is this possible with Moralis, or is Moralis mainly only working for window.ethereum and web3Enabled dapps?

Maybe you can try to use it from cloud code somehow.

This also worked for me but I wonder why… I just made the original server yesterday

Moralis speedy nodes are RIP no more :grinning: :grinning: :grinning: :grinning:
you can use infura alcvhemy nodes