Nodejs firesbase firestore does not retrieve any data using admin sdk - javascript

I am trying to read data from firestore database of firebase using admin sdk. The function returns nothing even I don't receive any error. The objective is to get the data using admin sdk and pass it to the browser using ejs variable.
Here is my code.
var admin = require('firebase-admin');
var serviceAccount = require("path to json file");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "mydatabase id"
});
var db = admin.firestore();
var courses = db.collection("courses");
app.get("/", function (req, res) {
var email = req.query.id;
courses.where("email", "==", email).get().then(function (data) {
console.log(data)
res.render("public/main.ejs", {
data: data
})
}).catch(function (error) {
console.log(error)
})
});

Try
app.get("/", function (req, res) {
var email = req.query.id;
var coursesRef = admin.firestore().collection('courses');
coursesRef.where("email", "==", email).get().then(function (data) {
data.forEach(doc => {
console.log(doc.data())
});
res.render("public/main.ejs", {
data: data
})
}).catch(function (error) {
console.log(error)
})
});

Related

how can i use express after an async function?

her i build my firebase and initialize it and finally was able to get the data from it but the problem was i couldnt use express.get() and json the data into the server im not sure what is the problem
let initializeApp = require("firebase/app");
let getAnalytics = require("firebase/analytics");
let firestore = require("firebase/firestore");
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = initializeApp.initializeApp(firebaseConfig);
const db = firestore.getFirestore();
const colRef = firestore.collection(db, "products");
async function getData() {
const querySnap = await firestore.getDocs(colRef);
var product = [];
querySnap.forEach((pr) => {
console.log(pr.data());
});
}
const express = require("express");
const ex = express();
let data = getData().then(
ex.get("/store", (req, res) => {
res.json(data);
ex.listen(5000, () => {
console.log(data);
})
})
);
i tried the code above nothing worked and got this error:
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read properties of undefined (reading 'method')
at Function.handle (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\router\index.js:139:34)
at Function.handle (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\application.js:181:10)
at app (C:\Users\hamdan\OneDrive\Desktop\hello\node_modules\express\lib\express.js:39:9)
i tired this
let data = getData().then(() => {
ex.get("/store", (req, res) => {
res.json(data);
});
ex.listen(5000, () => {
console.log(data);
});
});
it didnt give back an error but the problem is the data styed empty
you should put your server.listen in a different scope, not inside a get request scope. Your server should start before everything.
ex.get("/store", (req, res) => {
try{
res.json(data);
}catch(error){
console.log(error)
}})
ex.listen(5000, () => {
console.log(data);
})
`
Try this
ex.get("/store", async(req, res) => {
try{
let data = await get.Data()
console.log(data); //to see what you are recieving
res.json(data);
}catch(error){
console.log(error)
}})
ex.listen(5000, () => {
console.log("server running on port 5000);
})

(Node)Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
index.js
const express = require("express");
const { connectToDb, getDb } = require("./db");
// init app and middleware
const app = express();
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.sendStatus(200).json(mybook);
})
.catch(() => {
return res.sendStatus(500).send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!
both .sendStatus and .json will try to response to client. So the second call will result in this error.
Just use res.json(mybook) and res.send("there were an error") is enough.
In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").

React Native Duplicated data in Database

I am new to React Native. I created a Registration App connected to a local PostgreSql Database. I am using Formik for the form, after submitting the form it is recorded in the database. The app refreshes everytime I save the code. However after some refreshes, the data is duplicated in the database. I am using axios and a Rest API. Also using nodemon for the server.
Duplicated Data in the Database
POST REQUEST
const url = 'http://192.168.254.106:5000/users';
handleMessage(null);
handleMessage('Successfully Signed Up!', 'SUCCESS');
try {
const response = await axios.post(url, credentials);
} catch (error) {
handleMessage('An Error Occured.');
}
setSubmitting(false);
}, []);
REST API
const app = express();
const cors = require('cors');
const pool = require('./database');
//middleware
app.use(cors());
app.use(express.json());
//ROUTES
//create user
app.post('/users', async (req, res) => {
try {
const { fullname, email, birthdate, password } = req.body;
const user = await pool.query(
'INSERT INTO users(fullname, email, birthdate, password) VALUES($1, $2, $3, $4) RETURNING *',
[fullname, email, birthdate, password],
);
} catch (err) {
console.error(err.message);
}
});
//get all users
app.get('/users', async (req, res) => {
try {
const allUsers = await pool.query('SELECT * FROM users');
res.json(allUsers.rows);
} catch (err) {
console.error(err.message);
}
});
//get a user
app.get('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const user = await pool.query('SELECT * FROM users WHERE user_id=$1', [id]);
res.json(user.rows);
} catch (err) {
console.error(err.message);
}
});
//update a user
app.put('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const { email } = req.body;
const updateUser = await pool.query('UPDATE users SET email = $1 WHERE user_id=$2', [email, id]);
res.json('Updated!');
} catch (err) {
console.error(err.message);
}
});
//delete a user
app.delete('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const deleteUser = await pool.query('DELETE FROM users WHERE user_id=$1', [id]);
res.json('Deleted!');
} catch (err) {
console.error(err.message);
}
});
app.listen(5000, () => {
console.log('Server is up');
});

Axios NPM not fetching data express.js

I have a express.js route whose code is below: -
const path = require("path");
const express = require("express");
const hbs = require("hbs");
const weather = require("./weather");
const app = express();
app.get("/weather", (req, res) => {
if (!req.query.city) {
return res.send({
error: "City Not Found",
});
}
res.send({
currentTemp: weather.temp,
});
});
And I also have a file to fetch data from api using axios whose code is here
const axios = require("axios");
axios
.get(
"https://api.openweathermap.org/data/2.5/weather?q=samalkha&appid=91645b79f9eac8808153c90472150f2d"
)
.then(function (response) {
module.exports = {
temp: response.data.main.temp
}
})
.catch(function (error) {
console.log("Error Spotter");
});
As I am using res.send I should get a json with currentTemp and the value of current temp should be temperature that I will get from weather.js file but I am getting a blank json array.
Try this.
You'll get the temperature in the localhost:3000
If you want to render the data for EJS (or something) instead of .then((data) => res.json(data.main.temp)) use:
.then((data) => res.render("index", { weather: data })
--
const URL =
"https://api.openweathermap.org/data/2.5/weather?q=samalkha&appid=91645b79f9eac8808153c90472150f2d"
const express = require("express")
const axios = require("axios")
const app = express()
const PORT = 3000
app.get("/", (req, res) => {
axios
.get(URL)
.then((response) => response.data)
.then((data) => res.json(data.main.temp))
.catch((err) => console.log(err))
})
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}`)
})
module.exports is processed when the module is being defined. when you import weather, it does not exists therefore you get no data.
try to export a function which does the request and add a callback function as argument so you can pass the request result to it.
Change your weather.js to the following example:
const axios = require("axios");
let temperature;
async function getTemp() {
await axios
.get("https://api.openweathermap.org/data/2.5/weather?q=samalkha&appid=91645b79f9eac8808153c90472150f2d")
.then(function (response) {
temperature = response.data.main.temp
})
.catch(function (error) {
console.log("Error Spotter");
});
}
module.exports = {
temp: getTemp
}
This will actually return the fetched temperature.

Google oAuth2 UnhandledPromiseRejectionWarning: Error: No refresh token is set

This below is my auth.js route code to login via oAuth2 and it was working till this afternoon, now tonight started to throw error UnhandledPromiseRejectionWarning: Error: No refresh token is set.
const express = require("express");
const google = require('googleapis').google;
const jwt = require('jsonwebtoken');
const CONFIG = require("../config/passport-google");
const nf = require('node-fetch');
const gUser = require('../models/User-g');
const router = express.Router();
// Google's OAuth2 client
const OAuth2 = google.auth.OAuth2;
router.get("/youtube", function(req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(
CONFIG.oauth2Credentials.client_id,
CONFIG.oauth2Credentials.client_secret,
CONFIG.oauth2Credentials.redirect_uris[0]
);
// Obtain the google login link to which we'll send our users to give us access
const loginLink = oauth2Client.generateAuthUrl({
access_type: "offline", // Indicates that we need to be able to access data continously without the user constantly giving us consent
scope: CONFIG.oauth2Credentials.scopes // Using the access scopes from our config file
});
return res.render("./home/g-login", { loginLink: loginLink });
});
router.get("/youtube/callback", function(req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(
CONFIG.oauth2Credentials.client_id,
CONFIG.oauth2Credentials.client_secret,
CONFIG.oauth2Credentials.redirect_uris[0]
);
if (req.query.error) {
// The user did not give us permission.
return res.redirect("/");
} else {
oauth2Client.getToken(req.query.code, function(err, token) {
if (err) return res.redirect("/");
// Store the credentials given by google into a jsonwebtoken in a cookie called 'jwt'
res.cookie("jwt", jwt.sign(token, CONFIG.JWTsecret));
// return res.redirect("/get_some_data");
if (!req.cookies.jwt) {
// We haven't logged in
return res.redirect("/");
}
// Add this specific user's credentials to our OAuth2 client
oauth2Client.credentials = jwt.verify(req.cookies.jwt, CONFIG.JWTsecret);
// Get the youtube service
const service = google.youtube("v3");
const url = `https://www.googleapis.com/oauth2/v1/userinfo?access_token=${token[Object.keys(token)[0]]}`;
const get_data = async () => {
try {
const response = await nf(url);
const json = await response.json();
// save user to db
async (json, done) => {
const newUser = {
channelId: json.id,
channelEmail: json.email,
image: json.picture,
createdAt: Date.now()
}
try {
let user = await gUser.findOne({ channelId: json.id });
if(user){
done(null, user);
} else {
user = await gUser.create(newUser);
done(null, user);
}
} catch (err) {
console.log(err);
return res.redirect("../../500");
}
}
return json;
} catch (err) {
console.log(err);
return res.redirect("../../500");
}
};
// Get 50 of the user's subscriptions (the channels they're subscribed to)
service.subscriptions
.list({
auth: oauth2Client,
mine: true,
part: "snippet,contentDetails",
maxResults: 50
})
.then(async (response) => {
//.then(response => {
const diomerda = await get_data();
// Render the profile view, passing the subscriptions to it
return res.render("./user/dashboard", { subscriptions: response.data.items, diomerda: diomerda });
});
});
}
});
// Logout from Google
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
})
module.exports = router;
I tried to delete the app from the authorized apps inside my google account im using to test, and when i test the login again it now goes through all the steps of the login, it asks for permit, i accept twice and then it throws that error and the page looks like frozen in a loop

Categories

Resources