Exported functions are not defined. Parcel/Browserify - javascript

When I use a bundler to make my JS browser compatible my exported functions are not exported.
Error: (index):11 Uncaught TypeError: connect is not a function
at HTMLButtonElement.onclick ((index):11:46)
index.js (Same root file as index.html)
const {ethers} = require("ethers");
async function connect() {
if (typeof window.ethereum !== 'undefined') {
await ethereum.request({method: "eth_requestAccounts"});
}
}
module.exports = {
connect
}
index.html (Same root file as index.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<script src="./index.js" type="module"></script>
</head>
<body>
<button id="connect" onclick="connect()"> Connect </button>
</body>
</html>
Using parcel, which auto creates a dist file and starts a local server.
Also tried browserify and had same issue.

Parcel supports script tag/elements of type module.
This code works for me but window.ethereum is undefined, it's related to MetaMask no?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>HTML 5 Boilerplate</title>
</head>
<body>
<button id="connect">Connect</button>
<script type="module">
//Import your module
import something from "./index.js";
//Assign event listener to button
document
.getElementById("connect")
.addEventListener("click", function (event) {
something.connect();
});
console.log("something", something);
/* JavaScript module code here */
</script>
</body>
</html>
index.js
const { ethers } = require("ethers");
async function connect() {
console.log("Inside connect function");
console.log("window.etherum", window.ethereum);
console.log("ethers", ethers);
if (typeof window.ethereum !== "undefined") {
await ethereum.request({ method: "eth_requestAccounts" });
}
}
module.exports = {
connect,
};

Related

Uncaught (in promise) Error: 'args.method' must be a non-empty string

When trying to connect the metamask wallet with my local site i am getting this error
I am Using the eth_requestAccounts methord but getting the down err
inpage.js:8 Uncaught (in promise) Error: 'args.method' must be a non-empty string.
at o (inpage.js:8:31826)
at Object.invalidRequest (inpage.js:8:32276)
at l.request (inpage.js:1:37391)
at HTMLButtonElement.Connect (index.js:13:27)
this was the error being Printed on MY console
// HOW TO CONNECT YOUR METAMASK TO YOUR FRONTEND
const button = document.getElementById("ConnectButton");
//button.addEventListener('click',connect);
if (button) {
console.log("button successfully imported");
} else {
console.log("BUtton is not imported");
}
const Connect = async () => {
if (typeof window.ethereum !== "undefined") {
await window.ethereum.request({ methord: "eth_requestAccounts" });
button.innerHTML = "Connected";
} else {
button.innerHTML = "Pls install metamask";
}
};
button.addEventListener("click", Connect);
MY index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FUND ME</title>
</head>
<body>
<h1>HELLO WORLD
</h1>
<button id="ConnectButton">Connect</button>
<script src="index.js"></script>
</body>
</html>
MY index.html
It might likely be a typo error. You have methord instead of method

ReferenceError: document is not defined when connecting python backend to javascript frontend?

Im trying to make a program where the frontend is Node.js and the backend is Flask
Frontend:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>PreFab Davao</title>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Backend (The code I am trying to access):
#DBretriever.route('/getProjectDetails/<project_id>', methods = ['GET'])
def get_Project_Details(project_id): #gets project details from project ID
project_Details = []
found_Project = projects_collection.find_one({"project_id": project_id})
if found_Project == None:
print("Error Code: e0102db; Project ID Not Found")
return "e0102db"
else:
found_id = projects_collection.find_one({"project_id": project_id}, {"project_id": 1, "_id" : 0})
project_id = found_id['project_id']
project_Details.append(project_id)
found_name = projects_collection.find_one({"project_id": project_id}, {"project_name": 1, "_id" : 0})
project_name = found_name['project_name']
project_Details.append(project_name)
found_status = projects_collection.find_one({"project_id": project_id}, {"project_status": 1, "_id" : 0})
project_status = found_status['project_status']
project_Details.append(project_status)
found_tasks = projects_collection.find_one({"project_id": project_id}, {"tasks": 1, "_id" : 0})
tasks = found_tasks['tasks']
project_Details.append(tasks)
return project_Details
as a kind of bridge between the two, I created a new JS file contain functions the frontend can easily access (I did it because multiple people are working on this)
"Bridge" JavaScript File:
function getProjectDetails(){
const script = document.createElement("script");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
script.type = 'text/javascript'
$.ajax({
url:"/getProjectDetails/<project_id",
type: "GET",
dataType: "json",
success: function(data){
console.log(data)
}
});
}
getProjectDetails();
the problem arises when I try to call getProjectDetails() it gives me ReferenceError: document is not defined.
Is there anything I am missing?

Tessearct.js not working: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported

I am running this on Chrome and I use a node to set up a server.
Here is my HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/async/3.2.0/async.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<script src='https://unpkg.com/tesseract.js#v2.1.0/dist/tesseract.min.js'></script>
<script src="js/canvas-to-blob.min.js"></script>
<title>Slicer</title>
<script type="module" src="sketch.js"></script>
</head>
<body></body>
my javascript (copied from github.com/naptha/tesseract.js/blob/master/docs/examples.md)
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const rectangle = { left: 0, top: 0, width: 500, height: 250 };
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(imageURL, { rectangle });
console.log(text);
await worker.terminate();
})();
My error is:
Uncaught DOMException: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Here is what I have tried:
added crossOrigin = "Anonymous": it changed nothing
downloaded blueimp-canvas-to-blob
tried running the code alone on the terminal [I get this error "RuntimeError: abort(TypeError: Failed to parse URL from /path_to_project/node_modules/tesseract.js-core/tesseract-core.wasm)") // the file is there!
downloaded and used canvas-to-blob
What can I do to fix this?
Please use the tesseract.js 2.0.0 version.

how to solve Cannot read property 'name' of undefined in express js?

I'm not able to perform the routing with the parameter, I'm getting the error cant read property 'name'. I used the template engine twig.
Here is my template,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{About}}</title>
</head>
<body>
<P><h1>{{user}}</h1></P>
<P><h2>{{text}}</h2></P>
</body>
</html>
this is my main 'js' file-
const express=require('express')
const app=express()
app.use('./static',express.static('twig templet'))
app.set('view engine', 'twig')
app.set('views','./twig templet/views')
app.get('/',(res,req)=>{
req.render('index',{title:'EXPRESS',gred:'Hello-welcome to Express',mes:'This is twig file'})
})
app.get('/about/:name',(res,req)=>{
res.render('about',{About:'User',user:req.params.name,text:'This is twig file'})
console.log('user is:'+ req.params.name)
})
app.get('/calculation/:a-:b',(res,req)=>{
res.render('calculator',
{About1:'Calculation',
add:parseInt(req.params.a) + parseInt(req.params.b),
sub:parseInt(req.params.a) - parseInt(req.params.b),
mul:parseInt(req.params.a) * parseInt(req.params.b),
div:parseInt(req.params.a) / parseInt(req.params.b)})
//console.log('user is:'+ res.params.Name)
})
app.listen(5000,()=>{
console.log("server is running at 5000")
})
You have the callback values from the app.get() in the wrong order, it should be like this, you can omit the next though,
app.get('/about/:name',(req, res, next) => {}
That's it.

Exporting object in Webpack 5

I'm building a JS library with Webpack and trying to export an object.
import jwt_decode from "jwt-decode";
console.log(location.hash.replace('#', ''));
export var upstream = {
user: {
getUserDetails: () => {
if (location.hash) {
return jwt_decode(location.hash.replace('#', ''));
} else {
return null;
}
}
}
}
In my client-side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UpStream</title>
</head>
<body>
<script src="http://localhost:8080/app.js"> <!--server is up, connects fine-->
</script>
<script>
console.log(upstream);
</script>
</body>
</html>
The console.log(); statement works as intended, but I cannot access the upstream object. Any pointers?
To be able to access upstream via window or just upstream you would need to ensure you specify the export as a Library with libraryTarget of 'window'.
Hopefully that helps!

Categories

Resources