How to fetch correctly from server side in Node.js - javascript

I'd like to fetch/data and serverside fetch.
But I suffered following errors.
response.getCategory is not a function
const url = "/data";
.then(response => {
when we access /data, serverside fetch will be functioned.
const API_KEY="";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");
.then(response => response.json())
.then(json => { const quiz = new Quiz(json);
I can get result
getCategory_model History
I should pass same data from serverside to clientside
but method access succeeded only in serverside..
What is the cause of this ? and how can I fix it ? thanks..

You can't send objects with live methods over the wire as JSON. That is, if your server side Quiz object has a getCategory() method, it won't have one when you send it over to the client.
You'll need to serialize it, e.g.
categories: [quiz.getCategory(1)],

When you fetch data, your'e fetching data (usually as text).
When you create a new quiz with new Quiz(json) your'e reading the json text data and using Quiz to create code from the json text.
So in your first example you should get the text result, and then evaluate the result to json so that you can use getCategory() from Quiz
const url = "/data";
.then(data => data.json())
.then(json_text=> {
// here you use the text and parse to JSON
const data = JSON.parse(json_text)
// now you can create the Quiz object
const quiz = new Quiz(data)
console.log("getCategory_main.js", quiz.getCategory(1));


Fetch and Store files with IndexedDB

I need to download a list of files and store them locally with IndexedDB. I am using fetch to retrieve the files as follows:
cacheRecordings() {
var request ="database", 2);
request.onsuccess = event => {
var database =;
var transaction = database.transaction(["store"], 'readwrite'); //second step is opening the object store
this.objectStore = transaction.objectStore("store");
for (const url of this.urls) {
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const index = this.objectStore.index('path');
index.openCursor().onsuccess = function(event) { <-- Error is thrown here
this.objectStore.add(url, path);
.catch((error) => {
The above code results in the following two errors:
Failed to execute 'openCursor' on 'IDBIndex': The transaction is not active.
Failed to execute 'index' on 'IDBObjectStore': The transaction has finished
How do I store the fetched files using IndexedDB?
I found a relevant question - but it does NOT address my use case of fetched files.
TransactionInactiveError: Failed to execute 'add' on 'IDBObjectStore': The transaction is not active
My guess is that this happens because you are performing an async operation (the fetch) within a sync loop (the for)
To confirm this try storing a single file in the db without the loop. If that's successful, look into executing acync code within a loop

I'm getting the first response an empty list

I'm getting data from API like this:
const [software, setSoftware] = useState([]);
const id =;
useEffect(() => {
.then(response => response.json())
.then(data => {
}, [id]);
First response is an empty list, but the next response is my list from API. I tried to use useEffect because setSoftwares is asynchronous, but it didn't help.
So how can I get only my list?
I think you are sending incorrect id for the first time, try to console.log(id) it and check-in the console if id is valid or not.

How to make node-fetch to extract a specific parameter only?

I am trying to extract the priceChange of BNB rather than get the whole detail of the API (
I am using node-fetch model in Node js. The code is:
const fetch = require('node-fetch');
.then(res => res.text())
.then(text => console.log(text))
You need to use json method to get the data on node-fetch.
const fetch = require('node-fetch');
.then(res => res.json())
.then(instrument => {
Api that you provided is have json format.It is not a text format.Therefore you need to use
res.json() instead of using res.text().
return res.json();

Fetch recursion using javascript to call Google place API

I need to get a list of results from a Google place API request. The API allows 20 results per page ans I need all results available so I need to go to the next page.The next page is accessible from a token given in the response of the previous request.
I've implemented the code below:
function request(url){
return fetch(url)
.then((response) => response.json())
.catch((error) => console.log(error))
This is my recursive function:
export function getListOfActivitiesInACity(city_name,nextPageToken,datas){
const first_url = ''+city_name+'&key='+ API_TOKEN +'&language=fr'
const next_url = ''+nextPageToken+'&key='+ API_TOKEN
var url = nextPageToken ===''? first_url : next_url;
return request(url)
.then((data) => {
const newData = [...datas, data];
if(data["next_page_token"] !== undefined){
return getListOfActivitiesInACity(city_name,data["next_page_token"],newData);
return newData;
And then I call my function and print results
var datas=[];
.then(data => {console.log(data);})
The first iteration of the fetch works fine and gives me the good new url for the next fetch
(I tried it on my broser directy and it works)
But the second fetch return me this :
Object {
"html_attributions": Array [],
"results": Array [],
"status": "INVALID_REQUEST",
I really don't understand why it doesn't work , so please can anyone help Thanks

JavaScript Google Cloud Function: write Stripe values to Firebase

I'm new to JavaScript and I have written the following JS Google Cloud Function with the help of various resources.
This function handles a Stripe invoice.payment_succeeded event and instead of writing the entire data I am trying to save just both the sent period_start and period_end values back to the correct location in my Firebase DB (see structure below).
How can I write these two values in the same function call?
exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {
const hook = req.body.type;
const data =;
const status =;
const customer =;
const period_start =;
const period_end =;
console.log('customer', customer);
console.log('hook:', hook);
console.log('status', status);
console.log('data:', data);
console.log('period_start:', period_start);
console.log('period_end:', period_end);
return admin.database().ref(`/stripe_ids/${customer}`).once('value').then(snapshot => snapshot.val()).then((userId) => {
const ref = admin.database().ref(`/stripe_customers/${userId}/subscription/response`)
return ref.set(data);
.then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
.catch((error) => {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with StackDriver
return snap.ref.child('error').set(userFacingMessage(error));
.then((error) => {
return reportError(error, {user: context.params.userId});
HTTP type functions are terminated immediately after the response is sent. In your code, you're sending the response, then attempting to do more work after that. You will have to do all the work before the response is sent, otherwise it may get cut off.
If you just want to save the period_start and period_end values, instead of the entire data object, you can use the update() method (see
You should then modify your code as follows. (Just note that it is not clear from where you receive the userId value, since you don't show the stripe_ids database node in your question. I make the assumption that it is the value at /stripe_ids/${customer}. You may adapt that.)
exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {
const hook = req.body.type;
const data =;
const status =;
const customer =;
const period_start =;
const period_end =;
.then(snapshot => {
const userId = snapshot.val();
let updates = {};
updates[`/stripe_customers/${userId}/subscription/response/period_start`] = period_start;
updates[`/stripe_customers/${userId}/subscription/response/period_end`] = period_end;
return admin.database().ref().update(updates);
.then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
.catch((error) => {...});