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();

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