This question already has answers here:
ReferenceError: fetch is not defined
(25 answers)
Closed 1 year ago.
I tried using .then response and .catch but nothing worked. I am getting the below error when running test script .
I dont want to use node-fetch method
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
const json = await response.json();
Can anyone able to tell me what i am missing here?
(Use node --trace-warnings ... to show where the warning was created)
(node:12784) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (rejection id: 2)
(node:12784) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
fetch is not a javascript but a browser spec. See e.g. here for details on fetch.
The only solution is to use a node package as the mentioned node-fetch or use the default node http lib. From the docs:
var http = require('http');
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been received, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been received, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Related
I'm trying to compress and decompress the contents of a HTML file using zlib, to be able to send it over a post request to my database. I've got this code here, for example.
const { deflate, unzip } = require('zlib');
const input = '.................................';
deflate(input, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString('base64'));
});
const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString());
});
This is from NodeJS's official website, and it seems to work. It can compress and decompress the variable input. When I try to use this with my own variable, containing the HTML, deflating it worked; however, inflating it back into a string throws the error
(node:1353) UnhandledPromiseRejectionWarning: Error: invalid distance too far back
at Zlib.zlibOnError [as onerror] (zlib.js:182:17)
at processChunkSync (zlib.js:431:12)
at zlibBufferSync (zlib.js:168:12)
at Object.syncBufferWrapper [as unzipSync] (zlib.js:766:14)
at inflateString (/home/runner/woc-bot/functions.js:62:36)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:1353) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1353) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I think this means that the encoded string that my database returns is corrupted, so I tried to just send a simple encoded string to the database, fetch it back, and then inflate it again.
const { deflate} = require('zlib');
const input = 'Hellow worldw';
deflate(input, (err, buffer) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
console.log(buffer.toString('base64'));
});
I get eJzzSM3JyS9XKM8vykkpBwAjDAUr, so I send this to the database, and get it back. I unzip it, and it returns hellow worldw
I'm really not sure what's happening, I'm using Repl.it's database (plz dont judge me) and this has been killing me for the past two days.
I was trying to make a get request to the spotify API using axios in node.js. But, I always end up getting a 400 bad request. Could someone please help me out? The code snippet and the error are pasted below.
app.get('/api/search', async (req, res) => {
const spotify_search_one = await axios.get('https://api.spotify.com/v1/search', {
headers: {
'Authorization': keys.spotifyClientId
},
params: {
q: "face",
type: "track"
}
});
console.log(spotify_search_one);
})
The error is as follows
UnhandledPromiseRejectionWarning: Error: Request failed with status code 400
[0] at createError (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/core/createError.js:16:15)
[0] at settle (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/core/settle.js:17:12)
[0] at IncomingMessage.handleStreamEnd (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/adapters/http.js:236:11)
[0] at IncomingMessage.emit (events.js:322:22)
[0] at endReadableNT (_stream_readable.js:1187:12)
[0] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[0] (node:12697) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)
The error you‘re getting is that the Promise (axios.get) does not have a catch.
Therefore when the api call results in an error, you are not handling it in any way. What about trying it the asynchronous way?
I would send the api call axios.get(‘URL‘, ...) and then handle the response with .then and .catch.
I would suggest the following:
axios.get('https://api.spotify.com/v1/search', { headers: { 'Authorization': keys.spotifyClientId } })
.then(response => {
const spotify_search_one = response.data;
}).catch(err => {
console.error(err);
})
This will ask the Spotify-API for the desired data and then execute anything you write in the .then when the API-call was successful. The variable response contains the data (in this case the search results) which you can get with response.data.
If the API-call fails everything in .catch will be called. You could print the error or handle it in any other way then.
I'm trying to setup a stripe payment app using node and express, following the example here:
https://stripe.com/docs/payments/accept-a-payment#web
I created the route in my server side app code as indicated, and inserted the client-side code in my html file. I'm trying to create the app without a template engine, just html/css/javascript/node.
var response = fetch('/secret').then(function(response) {
return response.json();
}).then(function(responseJson) {
var clientSecret = responseJson.client_secret;
// Call stripe.confirmCardPayment() with the client secret.
});
I'm getting the following error:
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
I'm new to promises and not sure what the syntax with this code should be. Can I add
promise1.catch((error) => {
console.error(error);
});
Yes, adding a catch method at the end would catch the error(rejected Promise). What you suggested would work.
var response = fetch('/secret').then(function(response) {
return response.json();
}).then(function(responseJson) {
var clientSecret = responseJson.client_secret;
// Call stripe.confirmCardPayment() with the client secret.
}).catch(function(err) {
// Handle error
});
I played around with a package called instagram-profile-picture.
This is the code i used, straight from the npm website examples:
const ipp = require('instagram-profile-picture');
ipp('9gag').then(user => {
console.log(user);
// => https://scontent-sit4-1.cdninstagram.com/7...jpg
});
This used to work a couple days ago that i tested it.
Now, suddenly i get this error:
(node:1820) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'u
rl' of undefined
at got.then.res (C:\Users\User1\Desktop\testing npm\node_modules\insta
gram-profile-picture\index.js:15:49)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:1820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:1820) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
It is very weird because i changed nothing in the code.
So i tried a new installation
npm init -> npm install instagram-profile-picture
then the same code i posted previously and i still get the same error straight from the npm example.
So, the problem is because you are not logged in. Basically instagram changed the query API where if you have active session(logged in), then it will show more information, if not then it will not.
So, for 9gag if logged in:(just pasting relevant part)
{
"user": {
"pk": 259220806,
"hd_profile_pic_url_info": {
"url": "https://instagram.fbom20-1.fna.fbcdn.net/vp/777f85cb149a23d10da15f4af19ef407/5DE89E04/t51.2885-19/18645376_238828349933616_4925847981183205376_a.jpg?_nc_ht=instagram.fbom20-1.fna.fbcdn.net",
"width": 512,
"height": 512
}
},
"status": "ok"
}
But if you are logged out:
{
"user": {
"username": "9gag",
"profile_pic_url": "https://instagram.fbom20-1.fna.fbcdn.net/vp/c91395418170cbb196a69ac9dea359a4/5DD372FE/t51.2885-19/s150x150/18645376_238828349933616_4925847981183205376_a.jpg?_nc_ht=instagram.fbom20-1.fna.fbcdn.net"
},
"status": "ok"
}
But the library needs user.hd_profile_pic_url_info.url which is undefined.
Is the library going to work with teaks?
No unfortunately the code is quite straightforward in that library just fetching urls, you need to find one where you are providing some kind of authentication.
You can check out node-instagram,
EDIT2: The endpoint called from the library is https://i.instagram.com/api/v1/users/${userid}/info/ maybe a library out there will support this api. Or you can manually authenticate yourself using the apis and hit this url yourself.
You don't need a whole npm module for this. The api is pretty simple.
const https = require('https');
function getUserDetails(username) {
return new Promise(done => {
var data = [];
https.get(`https://www.instagram.com/${username}/?__a=1`, resp => {
resp.on('data', chunk => data.push(chunk));
resp.on('end', () => {
var json = JSON.parse(data.join(''));
done(json.graphql.user);
});
});
});
}
getUserDetails('9gag').then(user=>{
var bio = user.biography;
var full_name = user.full_name;
var profile_pic = user.profile_pic_url;
console.log(bio);
console.log(full_name)
console.log(profile_pic);
});
I am trying to send the response back to chatbot emulator from inside callback.
async getUserDetails(step){
console.log("inside get userdetaiuls modeiule")
this.userDBObject.password = step.result;
this.userDBMethod ( async function(response){
console.log("inside callback return");
console.log(response);
await step.context.sendActivity(response); // not able to do this step
return step.endDialog();
});
}
async userDBMethod(callback){
request.post('#',
{form:{key: 'hi'}}, function (error, response, body) {
callback("done");
});
}
The error which I'm getting is:
(node:17424) UnhandledPromiseRejectionWarning: TypeError: Cannot
perform 'get' on a proxy that has been revoked
at D:\LCI\Usecases\statementBalance\lionsbot-src\bot.js:384:32
at Request._callback (D:\LCI\Usecases\statementBalance\lionsbot-src\bot.js:410:17)
at Request.self.callback (D:\LCI\Usecases\statementBalance\lionsbot-src\node_modules\request\request.js:185:22)
at Request.emit (events.js:182:13)
at Request.EventEmitter.emit (domain.js:442:20)
at Request. (D:\LCI\Usecases\statementBalance\lionsbot-src\node_modules\request\request.js:1161:10)
at Request.emit (events.js:182:13)
at Request.EventEmitter.emit (domain.js:442:20)
at IncomingMessage. (D:\LCI\Usecases\statementBalance\lionsbot-src\node_modules\request\request.js:1083:12)
at Object.onceWrapper (events.js:273:13) (node:17424) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch(). (rejection id: 1) (node:17424) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
So how can I use await inside callback to send response back to the user.
Thanks !
I would recommend using Axios - a promise based HTTP client for node.js - rather than the request package. Since Axios is promise based, you can use async/await instead of callbacks. The resulting code falls more in line with the flow of the BotFramework. For more details, see the code snippet below and the Axios Documentation.
async getUserDetails(step){
this.userDBObject.password = step.result;
try {
const res = await axios.post('#', {form:{key: 'hi'}});
await step.context.sendActivity("Done");
} catch (error) {
console.log(error);
await step.context.sendActivity("Sorry, we were not able to complete your request.");
}
return step.endDialog();
}