Saving data to Moralis db fails

I have a strange issue. when I use user.save() for saving data to Moralis db I am blocked by CORS policy… whatever this means… I am using frp with frpc.ini and as web server I am using “lite-server”. I am using Chrome Brower.

I do not know whether there is private information in the tags… so I replaced them by the word “something”
Here is the developers console output, when I click on the save button:
localhost/:1 Access to XMLHttpRequest at ‘https: // something.moralis.io:2053/server/classes/_User/something’ from origin ‘http: // localhost:3000’ 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.
moralis.js:21595 POST https: // something.moralis.io:2053/server/classes/_User/something net::ERR_FAILED

My login session to Moralis works fine and I have an account…
Anybody had the same issue before?

Please post full JS and HTML code

Fiat2Crypto with Moralis
Connect wallet Profile
<div id="userInfo">
    <h4>User Profile</h4>
    <input type="text" id="txtUsername" required placeholder="Enter username">
    <input type="text" id="txtEmail" placeholder="Enter Email">
    <small>Optional</small>

    <img width="50" height="50" src="" id="imgAvatar" alt="User avatar">
    <label for="fileAvatar">Select Avatar</label>
    <input type="file" id="fileAvatar">

    <button id="btnLogout">Log out</button>
    <button id="btnCloseUserInfo">Close</button>
    <button id="btnSaveUserInfo">Save</button>
    
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/moralis.js"></script>
<script type="text/javascript" src="js/main.js"></script>

main.js:
Moralis.initialize(“jVc2O4nKwUFfmuCCebrK1nqlIhMCzdLs07OhcPgH”);
Moralis.serverURL = ‘https://0praksgszywd.moralis.io:2053/server’;

init = async () => {
hideElement(userInfo);
window.web3 = await Moralis.Web3.enable();
Moralis.Web3.getSigningData = () => ‘My custom message’;
//Dows not work: window.web3.getSigningData = () => ‘My custom message’;
initUser();
}

initUser = async () => {
if (await Moralis.User.current()) {
hideElement(userConnectButton); //If user is already logged in we do not need to show connect button
showElement(userProfileButton);
}
else {
showElement(userConnectButton);
hideElement(userProfileButton);
}
}

login = async () => {
try {
let user = await Moralis.Web3.authenticate(); //Bring up Metamask and Sign in to Moralis
console.log(“Ueer ETH Address:” , user.get(‘ethAddress’));
initUser();
}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 file  = userAvatarFile.files[0];
	const name = "photo.jpg";

	const avatar = new Moralis.File(name, file);
	user.set('avatar', avatar);		
}
try {
	await user.save();

}catch (err) {
	
console.log(err);
}

console.log("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(“btnUserInfo”);
userProfileButton.onclick = openUserInfo;

const userInfo = document.getElementById(“userInfo”);
const userUsernameField = document.getElementById(“txtUsername”);
const userEmailField = document.getElementById(“txtEmail”);
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;

init();

Moralis.Web3.authenticate().then(function (user) {
console.log(user.get(‘ethAddress’));
})

thanks but very difficult to read, please ensure all code is formatted

also - post entire HTML file, dont leave out anything

See this: https://discourse.stonehearth.net/t/discourse-guide-code-formatting/30587

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Fiat2Crypto with Moralis</title>
    <link rel="icon" type="image/vnd.microsoft.icon" href="img/favicon.ico" sizes="16x16 32x32 64x64">
</head>

<body>
    <div>
        <button id="btnConnect">Connect wallet</button>
        <button id="btnUserInfo">Profile</button>
    </div>

    <div id="userInfo">
        <h4>User Profile</h4>
        <input type="text" id="txtUsername" required placeholder="Enter username">
        <input type="text" id="txtEmail" placeholder="Enter Email">
        <small>Optional</small>

        <img width="50" height="50" src="" id="imgAvatar" alt="User avatar">
        <label for="fileAvatar">Select Avatar</label>
        <input type="file" id="fileAvatar">

        <button id="btnLogout">Log out</button>
        <button id="btnCloseUserInfo">Close</button>
        <button id="btnSaveUserInfo">Save</button>
        
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/moralis.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
</body>
</html>

main.js File:

Moralis.initialize("jVc2O4nKwUFfmuCCebrK1nqlIhMCzdLs07OhcPgH");
Moralis.serverURL = 'https://0praksgszywd.moralis.io:2053/server';

init = async () => {
	hideElement(userInfo);
	window.web3 = await Moralis.Web3.enable();
	Moralis.Web3.getSigningData = () => 'My custom message';
	//Dows not work:  window.web3.getSigningData = () => 'My custom message';
	initUser();
}

initUser = async () => {
	if (await Moralis.User.current()) {
		hideElement(userConnectButton); //If user is already logged in we do not need to show connect button
		showElement(userProfileButton);
	}
	else {
		showElement(userConnectButton);
		hideElement(userProfileButton);
	}
}

login = async () => {
	try {
		let user = await Moralis.Web3.authenticate(); //Bring up Metamask and Sign in to Moralis
		console.log("Ueer ETH Address:" , user.get('ethAddress'));
		initUser();
	}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 = ""; //not undefined, but empty string
		}

		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);
	//not check for double User names!
	user.set('username', userUsernameField.value);

	if(userAvatarFile.files.length > 0){
		const file  = userAvatarFile.files[0];
		const name = "photo.jpg";

		const avatar = new Moralis.File(name, file);
		user.set('avatar', avatar);		
	}
	try {
		await user.save();

	}catch (err) {
		
	console.log(err);
	}

	console.log("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("btnUserInfo");
userProfileButton.onclick = openUserInfo;

const userInfo = document.getElementById("userInfo");
const userUsernameField = document.getElementById("txtUsername");
const userEmailField = document.getElementById("txtEmail");
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;


init();

Moralis.Web3.authenticate().then(function (user) {
    console.log(user.get('ethAddress')); 
})

does the frpc.ini file maybe has something to do with it?
I have Ganache successfully connected to frpc… on this side everything looks fine…
Here is the log from the frp:
2021/06/05 12:57:24 [I] [service.go:304] [60236983ad9c49b5] login to server success, get run id [60236983ad9c49b5], server udp port [0]
2021/06/05 12:57:24 [I] [proxy_manager.go:144] [60236983ad9c49b5] proxy added: [ganache ssh]
2021/06/05 12:57:25 [I] [control.go:180] [60236983ad9c49b5] [ssh] start proxy success
2021/06/05 12:57:25 [I] [control.go:180] [60236983ad9c49b5] [ganache] start proxy success

I ran your code and substituted my own Moralis Server and saving the email and profile avatar worked for me. I commented out the authenticate call at the bottom as it’s redundant, but it still worked with it there.

This suggests to me there is something wrong with your ganache setup or your instance has been corrupted. With ganache it’s best to re-use the same workspace if using the graphical interface or if using the CLI pass a seed phrase and the deterministic flag.

Update to the latest Moralis Server version and refer to the Local Dev chain set up tutorial. If everything is set up properly try creating a new server instance.

Hi ! this solved the issue! Thanks! I had to delete the Server and install a new one also.
I use the line:
moralis-admin-cli connect-local-devchain --c ‘ganache’ --moralisApiKey 40FGa4YVKCgs50e --moralisApiSecret SECRET_KEY --frpcPath “/home/sven/GithubProjects/Moralis/frp_0.37.0_linux_amd64/frpc”

but then the console output is just:

“Starting connection to Ganache”

and no other information text afterwards like e.g. “connected to Ganache”

is this correct?
Also the --c ganache flag does not work. the script asks me for the server to connect and then whether to connect to Ganache or Hardhat

thanks a lot !

1 Like

Ok great that it worked