How can I make my external .js file work properly with my HTML file?

huangapple go评论53阅读模式
英文:

With Inline script working, How can I make my external .js file work properly with my HTML file?

问题

我目前正在开发一个使用IPFS和像Pinata这样的固定服务的网站。
我的上一个版本在本地交付或通过公共网关传递时运行完美无缺。
当尝试将上一个版本固定到Pinata时,我被告知不能使用内联JS。
因此,我的下一个版本包括一个名为app.js的外部JS文件。
我将此文件存储在与我的HTML文件(index.html)相同的文件夹中,并在固定到Pinata之前将其上传到IPFS进行测试。
无论我如何尝试调用.js文件路径,我都会每次都收到400或500的错误。

这是我用来调用文件的行。我正在边学边做,所以我对权限或可能导致无法检索此.js文件的其他问题了解不多。
在这一点上,代码基础仍然很简单,我确信我漏掉了一些非常明显的东西,只是忽视了。任何帮助都将不胜感激!

上一个版本(内联脚本)示例:LootCache.app

对于新版本,我尝试了我能想到的每个文件路径,但似乎都不起作用。我相信JS代码本身有效,因为我只是使用了上一个版本并将其外部化。我也知道至少大部分HTML正在工作,因为页面已经显示出来。唯一不起作用的是按钮和按下按钮时返回的数据。

HTML:

JavaScript:

英文:

I'm currently working on a website utilizing ipfs & pinning services like Pinata.
My last build works flawlessly when delivered locally or through a public gateway.
When trying to pin my last build to Pinata, I was informed I can't use inline JS.
So my next build includes an external JS file called app.js.
I'm storing this file within the same folder as my HTML file (index.html) and uploading to IPFS for testing purposes before pinning on Pinata.
I cannot for the life of me get this new build to work properly. No matter how I try to call the .js filepath, I either get 400s or 500s every single time.

    <script type="text/javascript" src="app.js"></script>

This is the line im using to call the file. I'm learning as I go so I don't know enough about permissions or other issues that may be causing this .js file to be unretreivable.
At this point the code base is still pretty simple and I'm sure I'm missing something very obvious and just overlooking. Any help would Be appreciated!

Last build (Inline Script) example: LootCache.app

Ive tried (With the new build) every file path I can think of and nothing seems to work. I believe the JS code itself works because I simply used the last builds and externalized it. I also know atleast most of the HTML is working since the page populates. The only thing that doesn't work is the button & the returned data when the button is pressed.

HTML :

    <!DOCTYPE html>
<html>
<head>
	<title>LootCache</title>
	<script type="text/javascript" src="app.js"></script>

	<style>
		body {
			background-color: black;
			margin: 0;
			padding: 0;
		}

		.container {
			max-width: 100%;
			margin: 0 auto;
			border: 5px solid gold;
			padding: 10px;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 100vh;
			overflow: auto;
		}

		h1 {
			font-size: 50px;
			font-weight: bold;
			color: gold;
			margin: 10px 0;
			display: flex;
			align-items: center;
		}

		.input-container {
			background-color: white;
			padding: 10px;
			margin: 10px 0;
			border-radius: 5px;
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 100%;
			box-sizing: border-box;
			max-width: 800px;
		}

		input[type=text] {
			width: 100%;
			padding: 10px;
			border: none;
			border-radius: 5px;
			box-sizing: border-box;
			font-size: 16px;
			margin-bottom: 10px;
		}

		button {
			background-color: gold;
			color: black;
			border: none;
			border-radius: 5px;
			padding: 10px;
			font-size: 16px;
			cursor: pointer;
		}

			.response {
			color: gold;
			font-size: 20px;
			margin-top: 10px;
			word-wrap: break-word;
			text-align: center;
		}

		img {
			display: block;
			max-height: calc(100vh - 300px);
			margin: 10px auto;
			object-fit: contain;
			max-width: 100%;
			height: auto;
		}
	</style>
</head>
<body>
	<div class="container">
		<img src="https://ipfs.io/ipfs/QmXjtBuhfDRZfTXZjF2dpJ4mSnmjj5RPow4qMY5X6ZQ6QU?filename=LootCache-1.png" alt="LootCache">
		<h1></h1>
		<div class="input-container">
			<label for="ethAddress">Enter Ethereum Address (No ENS):</label>
			<input type="text" id="ethAddress" name="ethAddress" placeholder="0x...">
			<button id="checkBalanceBtn">Check Your Stash!</button>
		</div>
		<div class="response" id="response"></div>
	</div>
</body>
</html>

JAVASCRIPT:

window.onload = function() {
async function getBalance(address) {
    const response = await fetch(`https://mainnet.infura.io/v3/fb3bba54ae0449c28400a4e28fb61e6c?module=account&action=balance&address=${address}`);
    const data = await response.json();
    return data.result;
}

function displayAddress() {
    var address = document.getElementById("ethAddress").value;
    var provider = new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/fb3bba54ae0449c28400a4e28fb61e6c");
    var web3 = new Web3(provider);
    web3.eth.getBalance(address, function(error, balance) {
        if (error) {
            document.getElementById("response").innerHTML = "Error: " + error.message;
        } else {
            var balanceInEther = web3.utils.fromWei(balance, "ether");
            var formattedBalance = parseFloat(balanceInEther).toFixed(4);
            document.getElementById("response").innerHTML = "Address: " + address + "<br>Balance: " + formattedBalance + " ETH";
        }
    });
}
}

答案1

得分: 0

你是否在localhost上进行测试并在开发者控制台中遇到CORS问题?可能需要启动服务器或在线托管进行测试,因为你正在加载本地文件。

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp

英文:

Are you testing on localhost and getting a CORS issue in the developer console? You may need to spin up a server or host online to test because you are loading local files.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp

答案2

得分: 0

已修复。这是一个不正确的文件路径和 "defer" 属性的组合。在纠正路径后,按钮仍然不起作用,但 .js 文件已加载。然后在调用 js 文件之前添加了 "defer" 和额外的 web3 脚本调用,以确保在调用脚本之前建立了 web3 连接。

英文:

Fixed. It was a combination of incorrect file path AND the "defer" attribute. After correcting the path, the button still didn't work but the .js loaded. Then added "defer" & and extra web3 script call BEFORE the js file call to make sure the web3 connection was established before the Scripts called

huangapple
  • 本文由 发表于 2023年4月20日 08:50:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定