load user.mail from Auth0 with async function - javascript

i want load the user.mail from Auth0 and safe there at a const. but I get a arrow. i don't see the error. can somebody help me to find the solution?
const userMailInfo = async () => {
auth0Client = await auth.createClient();
const result = await auth0Client.getUser().then(user => {
console.log('mail', user.email);
user.mail;
});
return result;
}
;(async () => {
const users = await userMailInfo()
console.log(users)
})()
i get follow error:
(node:19676) UnhandledPromiseRejectionWarning: ReferenceError: document is not defined

It looks like these errors are caused by code running on the server-side, where they do not have access to 'document' and the like. In SvelteKit, endpoints always run on the server, and therefore do not have access to all the elements in the 'Client API'.
To guard code from running on the server side, try calling it through OnMount(). I've linked a Sapper issue outlining some similar solutions, e.g., using if(process.browser). I am not sure if this works in SvelteKit, but may be worth checking out.
Note: It seems like the error occured outside of the provided code snippet.
SvelteKit Discord Server contains some discussions on the topic, try searching for 'UnhandledPromiseRejectionWarning ReferenceError'.
(for Sapper) https://github.com/sveltejs/sapper/issues/1226

Related

Spotify API Error. 401 Permissions missing. When Attempting to Play Track

I am trying to play a track on my app using spotify-web-api-node
const playSong = async () => {
// Verify access token with
console.log(spotifyApi.getAccessToken())
setCurrentTrackId(track.track.id);
setIsPlaying(true);
spotifyApi
.play({
uris: [track.track.uri],
})
.then((d) => console.log("hi", d))
.catch((e) => console.log("err", e));
};
https://github.com/caseysiebel/spotify-clone/blob/main/components/Song.tsx#L19
When I fire off this call to spotifyApi.play(), I am getting this error back WebapiRegularError: An error occurred while communicating with Spotify's Web API. Details: Permissions missing. with error code 401.
I have the accessToken and refreshToken set in my app. I am able to log in and get data from the API such as user, playslist and track data. But when I try to play a track, it's says I don't have permission.
I thought this might have something to do with how I've set the scopes in the Spotify API, but they look correct to me.
const scopes = [
"user-read-email",
"playlist-read-private",
"playlist-read-collaborative",
"user-read-email",
"streaming",
"user-read-private",
"user-library-read",
"user-top-read",
// "user-library-modify"
"user-read-playback-state",
"user-modify-playback-state",
"user-read-currently-playing",
"user-read-recently-played",
"user-read-playback-state",
"user-follow-read",
].join(",");
https://github.com/caseysiebel/spotify-clone/blob/main/lib/spotify.ts#L5
It seems like this has something to do with the scopes passed into the authorization LOGIN_URL but the streaming scope is definitely present and I can't see what the issue. It seems this way because certain API request work and others say they don't have permission.
Does anyone see what could be causing this issue with the missing persmisions issue and the Spotify API?
In lib/spotify.ts line 23 needed to be scope: scopes, not scopes: scopes,.
Actually using type checking probably would have been helpful here.
https://github.com/currenthandle/spotify-clone/commit/736108de1a1a132c43810d8415584f3be198609a#diff-b030a1ce426906990f8ed48fd8be76f54558b94141f4c811e679fef6661d396dR23
I think the problem is with your spotify.js file.
Here in clientId are you sure the name NEXT_PUBLICCLIENT_ID is right?
Shouldn't it be NEXT_PUBLIC_CLIENT_ID.
const spotifyApi = new SpotifyWebApi({
clientId: process.env.NEXT_PUBLICCLIENT_ID,
clientSecret: process.env.NEXT_PUBLIC_CLIENT_SECERT,
});
Try and let me know if this work or not?
You need to change NEXT_PUBLIC_CLIENT_ID & NEXT_PUBLIC_CLIENT_SECRET to SPOTIFY_CLIENT_ID & SPOTIFY_CLIENT_SECRET within your [...nextauth].js, spotify.js, & .env files.
Here's the NextAuth documentation with an example:
https://next-auth.js.org/providers/spotify

Error with my server file - Invalid URL: index.js

I am getting the following error when trying to run my server (index.js):
Error: TypeError [ERR_INVALID_URL]: Invalid URL: index.js
The code block is here:
app.get('/:url', async function (req, res) {
try {
return res.status(200).json(data);
} catch (ex) {
console.log(ex);
return res.status(500).json({ message : "Oops." });
}
With the specific line of code it is referring to is:
const site = await .open(decodeURIComponent(req.params.url));
Has anyone ever encountered this error before, and have any idea how to fix it in this context? Not sure how it is throwing an error for my entire index.js server
Note: This is an express app
The value of req.params.url is index.js.
A web browser can expand index.js into an absolute URL because it knows that it can use the URL of the current HTML document as the base URL.
You're running your code in Node.js. It doesn't run inside a document. There is no base URL.
You need to provide an absolute URL (e.g. http://example.com/index.js) yourself.
That said, I suspect wappalyzer may require that you give it the URL to an HTML document not a JS file.
Well, since there isn't much that i can see about your usage, I'm just going to assume you went to something like http://localhost/index.js.
The problem now is, that wappalyzer does not actually get a valid url. It gets index.js without any form of protocol (http/https/ws/wss...). This means it doesn't know what to do and tells you that the url you provided is invalid.
In order to fix this go to http://localhost/https%3A%2F%2Flocalhost%2Findex.js or append https:// or something similar to your parameter.

Unable to get Notify data using Noble

Can't receive any notifications sent from the Server peripheral.
I am using ESP32 as Server with the "BLE_notify" code that you can find in the Arduino app (File> Examples ESP32 BLE Arduino > BLE_notify).
With this code the ESP32 starts notifying new messages every second once a Client connects.
The client used is a Raspberry Pi with Noble node library installed on it (https://github.com/abandonware/noble). this is the code I am using.
noble.on('discover', async (peripheral) => {
console.log('found peripheral:', peripheral.advertisement);
await noble.stopScanningAsync();
await peripheral.connectAsync();
console.log("Connected")
try {
const services = await peripheral.discoverServicesAsync([SERVICE_UUID]);
const characteristics = await services[0].discoverCharacteristicsAsync([CHARACTERISTIC_UUID])
const ch = characteristics[0]
ch.on('read', function(data, isNotification) {
console.log(isNotification)
console.log('Temperature Value: ', data.readUInt8(0));
})
ch.on('data', function(data, isNotification) {
console.log(isNotification)
console.log('Temperature Value: ', data.readUInt8(0));
})
ch.notify(true, function(error) {
console.log(error)
console.log('temperature notification on');
})
} catch (e) {
// handle error
console.log("ERROR: ",e)
}
});
SERVICE_UUID and CHARACTERISTIC_UUID are obviously the UUIDs coded in the ESP32.
This code sort of works, it can find Services and Characteristics and it can successfully connect to the peripheral, but it cannot receive messages notifications.
I also tried an Android app that works as client, from that app I can get all the messages notified by the peripheral once connected to it. So there is something missing in the noBLE client side.
I think there is something wrong in the on.read/on.data/notify(true) callback methods. Maybe these are not the methods to receive notifications from Server?
I also tried the subscribe methods but still not working.
The official documentation is not clear. Anyone could get it up and running? Please help.
on.read/on.data/ are event listeners. There is nothing wrong with them. They are invoked when there is a certain event.
For example adding characteristic.read([callback(error, data)]); would have invoked the on.read.
From the source:
Emitted when:
Characteristic read has completed, result of characteristic.read(...)
Characteristic value has been updated by peripheral via notification or indication, after having been enabled with
characteristic.notify(true[, callback(error)])
I resolve using the following two envs NOBLE_MULTI_ROLE=1 and NOBLE_REPORT_ALL_HCI_EVENTS=1 (see the documentation https://github.com/abandonware/noble)

ReactJS: How to fix TypeError: data is not iterable

I have two applications running at the same time. The first one is fetching APIs from vessel-finder and finding only a specific number of boats.
The second application is the user interface used to visualize data from the fetch, specifically latitude and longitude of boats.
The problem I have is that the fetch seems to arrive correctly to the end point but that throws an error of TypeError: data is not iterable as also shown here on the terminal.
It seems that the problem might be the API fetch. Below the code I am using for that:
router.get('/hello', async function(req, res, next) {
try {
const { data } = await axios.get(
'https://api.vesselfinder.com/vesselslist?userkey=KEY'
);
const [ metaData, ships ] = data;
console.log(data);
res.send(data);
} catch (error) {
res.send(error);
console.log(error);
}
});
module.exports = router;
While investigating what the problem might be, I came across this source which also uses axios to get the call to the API.
I wonder now if the fetch I am making is basically incomplete and because of that, data is not iterable...
Also from this post I was able to handle a missing Promise using a try-catch block that was preventing me from compiling.
Is the problem due to a missing axios.get('API call').then.setState instruction I am missing?, if so how could I fix that?
Thank you very much for pointing to the right direction for solving this problem.
look out for this line in your code -
const [ metaData, ships ] = data;
perform object destructuring either between two objects or between two arrays. You are trying it out between an array and an object, which is a flaw.
For more details, check https://javascript.info/destructuring-assignment#object-destructuring

How do I save user account information to firebase?

I've made a Google Log in for my actions on google project, and I want to save the account info to a firestore database.
I looked at Google's example of how to do this (example here, at the very bottom under heading "Handle Data Access Requests"), but when you actually try to deploy it to firebase, you realize that it's actually has invalid syntax (or at least that's what the dialogflow inline editor is saying.....)
Here's what the error says specifically when I try to deploy this code:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:34
app.intent('Get Sign In', async (conv, params, signin) => {
^
SyntaxError: Unexpected token (
Any suggestions?
Thanks for the help!
Please note: I am using only the code that the tutorial has said to PLUS
I added the actions on google library and the fulfillment line (ie:
// Other libraries...
const {
dialogflow,
BasicCard,
Permission,
Suggestions,
Carousel,
SignIn
} = require('actions-on-google');
// ** code from tutorial / link **
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app)
I figured out how to do this, however it was a different method than the actions on google example. If anyone knows how to do this easier or knows what was wrong with the code in the link I posted (if anything..) please let me know / add an answer!
I decided to just write to firestore directly and put it under a "Get Signin" function (also mentioned in the tutorial for dialogflow).
Here is the function I used to get the user to sign in and also log the information into firestore:
app.intent('Get Signin', (conv, params, signin) => {
if (signin.status === 'OK') {
const payload = conv.user.profile.payload;
conv.ask(`Welcome back ${payload.name}. What can I help you with??`);
const databaseEntry = conv.user.profile.payload; // Account info, loaded to firestore
const accountRef = db.collection('Accounts').doc('account_info'); //How you want the info in firestore to appear
return db.runTransaction(t => {
t.set(accountRef, {entry: databaseEntry});
return Promise.resolve('Write complete');
}).then(doc => {
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
});
} else {
conv.close(`To continue, you need to make an account with the app.`);
}

Categories