Axios Cannot read properties of undefined - javascript

I am trying to build my own staking page for my NFT project. I cloned a repo named gem-farm from github. But I am facing with an issue when I start it at localhost.
index.js?9d03:45 TypeError: Cannot read properties of undefined (reading 'protocol')
at isURLSameOrigin (isURLSameOrigin.js?3934:57:1)
at dispatchXhrRequest (xhr.js?b50d:145:1)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js?b50d:15:1)
at dispatchRequest (dispatchRequest.js?5270:58:1)
at Axios.request (Axios.js?0a06:108:1)
at Axios.<computed> [as get] (Axios.js?0a06:129:1)
at Function.wrap [as get] (bind.js?1d2b:9:1)
at _callee$ (cluster.ts?b691:26:1)
at c (blocto-sdk.umd.js?758a:3:1)
I think it is caused by this file since it is the only file using axios
Where it imports axios:
import { TOKEN_PROGRAM_ID } from '#solana/spl-token';
import axios from 'axios';
import { programs } from '#metaplex/js';
This is where it uses axios:
async function getNFTMetadata(
mint: string,
conn: Connection,
pubkey?: string
): Promise<INFT | undefined> {
// console.log('Pulling metadata for:', mint);
try {
const metadataPDA = await Metadata.getPDA(mint);
const onchainMetadata = (await Metadata.load(conn, metadataPDA)).data;
const externalMetadata = (await axios.get(onchainMetadata.data.uri)).data;
return {
pubkey: pubkey ? new PublicKey(pubkey) : undefined,
mint: new PublicKey(mint),
onchainMetadata,
externalMetadata,
};
} catch (e) {
console.log(`failed to pull metadata for token ${mint}`);
}
}
I tried it on both PC & Macos. I couldn't find any solution. Thanks.

Related

#aws-sdk/client-s3 S3Client returning Error TypeError: Cannot read properties of undefined (reading 'send')

Following along with the AWS-SDK examples/documentation in a Gatsby app, I have the workflow below setup to upload a file to my S3 bucket from the client directly however, the const data = await client.send(...) is returning Error TypeError: Cannot read properties of undefined (reading 'send') even though client definitely exists.
AWS is a new frontier, forgive me if my mistake is painfully obvious.
full error:
Error TypeError: Cannot read properties of undefined (reading 'send')
at eval (fromCognitoIdentityPool.js:26:1)
at step (tslib.es6.js:102:1)
at Object.eval [as next] (tslib.es6.js:83:1)
at fulfilled (tslib.es6.js:73:1)
Client initializer and accompanying uploader AJAX:
import { PutObjectCommand, S3Client } from "#aws-sdk/client-s3";
import { fromCognitoIdentityPool } from "#aws-sdk/credential-provider-cognito-identity";
const client = new S3Client({
region: process.env.GATSBY_AWS_S3_REGION,
credentials: fromCognitoIdentityPool({
clientConfig: { region: process.env.GATSBY_AWS_S3_REGION },
identityPoolId: process.env.GATSBY_AWS_USER_POOL_ID,
})
})
// Upload file to specified bucket.
export const run = async ({ email, photo }) => {
const uploadParams = {
Bucket: process.env.GATSBY_AWS_BUCKET_NAME,
Key: email + photo.name,
Body: photo,
};
try {
const data = await client.send(new PutObjectCommand(uploadParams));
console.log("Success", data);
return data;
} catch (err) {
console.log("Error", err);
}
};
The mistake was in the import:
import { fromCognitoIdentityPool } from "#aws-sdk/credential-provider-cognito-identity";
when it should have been:
import { fromCognitoIdentityPool } from "#aws-sdk/credential-providers";

Error trying to login on Azure: BrowserAuthError

I'm getting an error trying to login with Azure + TypeScript/JavaScript. The problem is when the user logs in and needs to get redirected to another page. When the response from login is OK, the page remains blank and I need to refresh manually.
This is my config file:
import { Configuration, LogLevel } from "#azure/msal-browser"
export const msalConfig:Configuration = {
auth: {
clientId: process.env.AZURE_CLIENT_LOGIN || "",
authority: "https://login.microsoftonline.com/" + process.env.AZURE_AUTH_LOGIN,
redirectUri: "/admin/dashboard"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level: any, message: any, containsPii: any) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
}
export const loginRequest = {
scopes: ["User.Read"]
};
export const graphConfig = {
graphMeEndpoint: "Enter_the_Graph_Endpoint_Herev1.0/me"
};
And this is my index page:
import React, { useEffect } from 'react';
import type { NextPage } from "next";
import { useRouter } from 'next/router';
import { useMsal } from '#azure/msal-react';
import { useIsAuthenticated } from '#azure/msal-react';
import { loginRequest } from '../services/azureLoginApi';
const Home: NextPage = () => {
const router = useRouter()
const { instance } = useMsal()
const isAuthenticated = useIsAuthenticated()
const redirectToAzureLogin = () => {
instance.loginRedirect(loginRequest).catch((e:any) => {
console.log(e);
});
}
const redirectToDashboard = () => {
router.push('/admin/dashboard')
}
useEffect(()=>{
if(isAuthenticated)
redirectToDashboard()
else
redirectToAzureLogin()
},[])
return (
<div className="index">
</div>
);
};
export default Home;
On console, I get this message:
BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. For more visit: aka.ms/msaljs/browser-errors.
at BrowserAuthError.AuthError [as constructor] (AuthError.js?d98c:27:1)
at new BrowserAuthError (BrowserAuthError.js?be02:197:1)
at Function.BrowserAuthError.createInteractionInProgressError (BrowserAuthError.js?be02:264:1)
at BrowserCacheManager.setInteractionInProgress (BrowserCacheManager.js?6011:886:23)
at PublicClientApplication.ClientApplication.preflightInteractiveRequest (ClientApplication.js?9c57:777:1)
at PublicClientApplication.ClientApplication.preflightBrowserEnvironmentCheck (ClientApplication.js?9c57:762:1)
at PublicClientApplication.eval (ClientApplication.js?9c57:220:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.ClientApplication.acquireTokenRedirect (ClientApplication.js?9c57:214:25)
at PublicClientApplication.eval (PublicClientApplication.js?1b7b:63:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.loginRedirect (PublicClientApplication.js?1b7b:58:25)
at redirectToAzureLogin (index.tsx?db76:18:14)
at eval (index.tsx?db76:31:7)
at invokePassiveEffectCreate (react-dom.development.js?61bb:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994:1)
at invokeGuardedCallback (react-dom.development.js?61bb:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js?61bb:23574:1)
at unstable_runWithPriority (scheduler.development.js?3069:468:1)
at runWithPriority$1 (react-dom.development.js?61bb:11276:1)
at flushPassiveEffects (react-dom.development.js?61bb:23447:1)
at eval (react-dom.development.js?61bb:23324:1)
at workLoop (scheduler.development.js?3069:417:1)
at flushWork (scheduler.development.js?3069:390:1)
at MessagePort.performWorkUntilDeadline (scheduler.development.js?3069:157:1)
The page remains blank until I give a manual refresh on it. With the manual refresh, the redirect works, but without it the page remains freezed.
I've tried some solutions on StackOverflow and other blogs but didn't work out.
Thank you all for any help you may give!
change instance.loginRirect to instance.loignPopup, that would solve that
Problem solved: the point was the useEffect without dependencies. Adding it solved the problem, now the redirect works without needing to manually update the page.

TypeError: Cannot read property 'name' of undefined discord.js command handler

Okay So I am getting an error this worked Just Yesterday and out of nowhere it broke.....
Now here is the error
/app/handlers/command.js:8
bot.commands.set(pull.config.name, pull);
^
TypeError: Cannot read property 'name' of undefined
at load (/app/handlers/command.js:8:42)
at /app/handlers/command.js:12:75
at Array.forEach (<anonymous>)
at module.exports (/app/handlers/command.js:12:62)
at /app/index.js:16:72
at Array.forEach (<anonymous>)
at Object.<anonymous> (/app/index.js:16:33)
at Module._compile (internal/modules/cjs/loader.js:759:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
Each Command open up with
module.exports = {
config: {
name: "command name"
Now here is the code in the command handler
const { readdirSync } = require("fs")
module.exports = (bot) => {
const load = dirs => {
const commands = readdirSync(`./commands/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of commands) {
let pull = require(`../commands/${dirs}/${file}`);
bot.commands.set(pull.config.name, pull);
if (pull.config.aliases) pull.config.aliases.forEach(a => bot.aliases.set(a, pull.config.name));
};
};
["currency", "fun", "holiday", "info", "moderation"].forEach(x => load(x));
};
Okay The error was my project did not save for some reason so I messed up evrything is fine but I just have to get everything to save again.
It looks like maybe you didn't define the name variable, try defining it just before the code, since its returning undefined in the error.

Calling async method from instanced Object gives error: TypeError: Object(...) is not a function

I am currently developing an app for educational purposes and facing a problem that is probably trivial but can't get around and solve it.
So basically I am trying to fetch some data from an external API (using Axios for that). I have divided my code into modules that I am exporting to index.js file and from that, I am instancing new Object and calling my async method getResults() which in return should give me data from API. From that point a get error
TypeError: Object(...) is not a function.
Here is an example code:
Module Search.js:
export default class Search {
constructor(query, num) {
this.query = query;
this.num = num;
}
async getResults() {
const url = 'API_URL';
const key = 'API_KEY';
try {
const res = await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
this.result = res.data.results;
console.log(this.result);
} catch (error) {
console.log(error);
}
}
}
And here is index.js file:
import Search from "./models/Search";
const s = new Search('cheese', 2);
s.getResults()
And finally error in console:
TypeError: Object(...) is not a function
at Search._callee$ (Search.js:42)
at tryCatch (runtime.js:65)
at Generator.invoke [as _invoke] (runtime.js:303)
at Generator.prototype.<computed> [as next] (runtime.js:117)
at asyncGeneratorStep (Search.js:5)
at _next (Search.js:7)
at eval (Search.js:7)
at new Promise (<anonymous>)
at Search.eval (Search.js:7)
at Search.getResults (Search.js:65)
I am probably doing something wrong here, any help and insight would be appreciated. Thanks.
await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
This is the line creating error,
axios is an object which you are trying to use as function
You probably wish to use get/post method provided by axios to call your endpoint
await axios.get(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
You can have a look how you want to use axios https://github.com/axios/axios

Ionic 4 plugin - Object is not a function

I am trying to use ionic 4 google plus plugin to log in with google, but when I call :
googleLogin(){
this.nativeGoogleLogin();
}
async nativeGoogleLogin(): Promise<void> {
console.log('trying to log in with google');
const creds = {
'webClientId': '125618127989-slbv15359v8g76elj0664agipfedc5cn.apps.googleusercontent.com',
'offline': true,
'scopes': 'profile email'
}
try {
await this.googlePlus.login(creds).then(res => console.log(res)) // This line gets error
} catch(err) {
console.log(err)
}
}
I get error :
TypeError: Object(...) is not a function
at GooglePlus.login (index.js:27)
at BuyerLoginPage. (buyer-login.ts:109)
at step (buyer-login.module.ts:26)
at Object.next (buyer-login.module.ts:26)
at buyer-login.module.ts:26
at new t (polyfills.js:3)
at webpackJsonp.555.__awaiter (buyer-login.module.ts:26)
at BuyerLoginPage.webpackJsonp.555.BuyerLoginPage.nativeGoogleLogin
(buyer-login.ts:101)
at BuyerLoginPage.webpackJsonp.555.BuyerLoginPage.googleLogin (buyer-login.ts:117)
at Object.eval [as handleEvent] (BuyerLoginPage.html:141)
I mean, it isn't even firing cordova plugin, it's just error which says nothing to me. Anyone help ?

Categories

Resources