how can i use express after an async function? - javascript

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);
})

Related

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

I built a crud application using mern stack. Then I tried the search operation for the application but it show me this error:
BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
This is my client side code:
Search.js
import React from 'react';
const Search = () => {
const searchHandle = e => {
e.preventDefault();
const userName = e.target.search.value;
fetch(`http://localhost:5000/user/${userName}`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
console.log(typeof(userName));
}
return (
<div className='px-3 py-2 w-3/4'>
<h1 className='text-3xl font-bold mb-3'>Search User:</h1>
<form onSubmit={searchHandle}>
<input className='bg-gray-200 rounded p-2 w-3/4' type="search" name="search" id="name" />
<button className='bg-blue-500 mx-2 py-2 px-4 rounded' type='submit'>Search</button>
</form>
</div>
);
}
export default Search;
This is my server side code:
const expres = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const app = expres();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(expres.json())
const uri = "mongodb+srv://user:##cluster0.moilkdv.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
async function run() {
try {
const userCollection = client.db('simpleNode').collection('users');
// get all users
app.get('/user', async (req, res) => {
const cursor = userCollection.find({});
const users = await cursor.toArray();
res.send(users);
})
// get a specific user for update
app.get('/user/:id', async (req, res) => {
const updateId = req.params.id;
const updateQuery = { _id: ObjectId(updateId)}
const user = await userCollection.findOne(updateQuery);
res.send(user);
})
// updating user
app.put('/user/:id', async (req, res) => {
const userId = req.params.id;
const user = req.body;
const filter = { _id: ObjectId(userId) };
const options = { upsert: true };
const updatedUser = {
$set: {
name: user.name,
address: user.address
}
}
const result = await userCollection.updateOne(filter, updatedUser, options);
res.send(result);
})
// creating users
app.post('/user', async (req, res) => {
console.log('post api called');
const Nuser = req.body;
const result = await userCollection.insertOne(Nuser);
res.send(result);
});
// search query
app.get('/user/:name', (req, res) => {
const searchName = req.params.name;
console.log(searchName);
})
// deleting user
app.delete('/user/:id', async(req, res) => {
const userId = req.params.id;
const deleteQuery = { _id: ObjectId(userId)};
const resut = await userCollection.deleteOne(deleteQuery);
console.log("Delete complete of: ", userId);
console.log(resut);
res.send(resut);
})
}
finally {
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Server is running');
})
app.listen(port);
Please help to solve this error.
That request is sent to app.get('/user/:id') route.
:id or :name is just the name of the parameter.
We have to setup another route for searching, eg: change app.get('/user/:name') to app.get('/user/search/:name')

axios post data successfully but failed to assign location after response success instead res.json rendered to client as html page

axios script.js file
const creatClient = async (client) => {
try {
const res = await axios({
method: 'POST',
withCredentials: true,
url: '/[url]',
data: client,
}).then(location.assign('/[newUrl]'));
} catch (error) {
console.log(error);
}
};
submitbtn.addEventListener('click', (e) => {
e.preventDefault;
const name = document.getElementById('name').value;
const phone = document.getElementById('phone').value;
const createdATT = new Date(document.getElementById('date').value);
const followUp = new Date(document.getElementById('date2').value);
const images = document.getElementById('img').value;
const insurance = document.getElementById('insurance').value;
const client = { name, phone, insurance, images, createdATT, followUp };
console.log(client);
client ? creatClient(...client) : console.log('no object created');
});
controller file
the console log for req.body [Object: null prototype] {*** the object ***}
const multer = require('multer');
const Client = require('../models/clientModel');
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public/img');
},
filename: (req, file, cb) => {
const ext = file.mimetype.split('/')[1];
cb(null, `user-${Date.now()}.${ext}`);
},
});
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
} else {
cd(console.log('select image'), false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
exports.uploadImages = upload.single('images');
//
exports.createClients = async (req, res, next) => {
try {
if (req.file) req.body.images = req.file.filename;
const newClient = { ...req.body };
await Client.create(req.body).then(
res.status(200).json({
status: 'success',
newClient,
})
);
} catch (err) {
console.log(err);
}
};
also with postman sending request give success response with no errors
i've tried location.replace() but also it didn't work for me
and is there another trick from server to get to the desired location out from client side
then accepts a callback as a parameter.
then(() => location.assign('/[newUrl]'))

firebase.auth() - Syntax error "unexpected token ."

I am trying to follow a video on youtube called "Full Stack React & Firebase Tutorial - Build a social media app" and I am having trouble with the code for adding new users to firebase..
My code looks like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "socialtutorial.firebaseapp.com",
databaseURL: "https://socialtutorial.firebaseio.com",
projectId: "socialtutorial",
storageBucket: "socialtutorial.appspot.com",
messagingSenderId: "SenderID",
appId: "1:848457683801:web:a276f7436db03ac500b248"
}
const firebase = require('firebase');
firebase.initializeApp(firebaseConfig);
app.get('/challenges', (req, res) => {
admin
.firestore()
.collection('challenges')
.orderBy('challengeCreated', 'desc')
.get()
.then(data => {
let challenges = [];
data.forEach(doc => {
challenges.push({
challengeId: doc.id,
challengeName: doc.data().challengeName,
challengeDescription: doc.data().challengeDescription,
challengeCreated: doc.data().challengeCreated
});
});
return res.json(challenges);
})
.catch (err => console.error(err));
})
app.post('/challenge', (req, res) => {
const newChallenge = {
challengeName: req.body.challengeName,
challengeDescription: req.body.challengeDescription,
challengeCreated: new Date().toISOString()
};
admin.firestore()
.collection('challenges')
.add(newChallenge)
.then(doc => {
res.json({message: `document ${doc.id} created successfully`});
})
.catch(err => {
res.status(500).json({error: 'something went wrong'});
console.error(err);
})
})
//Sign Up Route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
userName: req.body.userName
}
//TODO Validate
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({message: `user ${data.user.uid} signed up successfully`});
})
.catch(err) => {
console.error(err);
return res.status(500).json({error: err.code})
}
})
exports.api = functions.region('europe-west1').https.onRequest(app);
Now, when I try "firebase deploy" or "serve" I get an unexpected token error. The error is the "." after firebase... I must have missed something in the code above, but I can't see it for the life of me. I know this is a stupid mistake and I should be able to fix it on my own, but I literally can't see, where the error comes from...
Any help from you guys? Thanks a lot in advance!
I'm not sure if maybe you copied pasted to the question incorrectly from your editor but the only thing I see is the last catch of your code. It seems you never pass a callback to it.
you defined it as follows
.catch(err) => {
but it should be
.catch(err => {

Nodejs firesbase firestore does not retrieve any data using admin sdk

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)
})
});

Cloud function: HTTP trigger inconsistent batch commit

I'm trying to update multiple collections in my Firestore and RTDB by triggering Google cloud function through an HTTP request, and I've done some several times of testing, but the batch commit works from time to time. I've also tried running test excluding RTDB update from the code, but nothing changes much.
If something goes wrong, I get the following error message with status code 500.
Error: Cannot modify a WriteBatch that has been committed.
Here's the example code:
Server-side code
'use strict';
module.exports = ({ admin, cors, express, functions }) => {
const app = express();
const fireStore = admin.firestore();
const rtdb = admin.database();
const apps = fireStore.collection('apps');
const users = fireStore.collection('users');
const batch = admin.firestore().batch();
app.use(cors({ origin: true }));
...
app.post('/', (req, res) => {
const uid = req.user.user_id;
const data = req.body;
const appsRef = apps.doc(uid);
const usersRef = users.doc(uid);
const activityState = {
currentActiveStatus: data.activityState.currentActiveStatus,
usingApp: data.activityState.usingApp
};
const appState = {
emailVerified: data.user.emailVerified
};
const userState = {
displayName: data.user.displayName,
photoURL: data.user.photoURL,
currentActiveStatus: data.user.currentActiveStatus,
lastLoginAt: admin.firestore.FieldValue.serverTimestamp()
};
batch.update(appsRef, appState);
batch.update(usersRef, userState);
return batch.commit().then(() => {
console.log('Batch commit finished!');
return admin.database().ref(`status/${uid}`).update(activityState).then(() => {
res.status(201).send({ message: 'Successfully Initialize Default State' });
});
}).catch(err => console.log('Err:', err));
});
return functions.https.onRequest(app);
};
Client-side code
const data = {
activityState: {
currentActiveStatus: "online",
usingApp: "true"
},
user: {
displayName: this.displayName,
photoURL: this.photoURL,
currentActiveStatus: "online",
emailVerified: "true"
}
};
this.userService.updateUserProfile(this.displayName, this.photoURL).then((accessToken) => {
const url = 'https://us-central1/dbname/cloudfunctions.net/functionname';
this.http.post(url, JSON.stringify(data), {
headers: {'Authorization': accessToken, 'Content-Type': 'application/json; charset=utf-8'}
}).subscribe((res) => {
// Worked well
}, (err) => {
// Went wrong
});
});
Error message in details
Error: Cannot modify a WriteBatch that has been committed.
at WriteBatch.verifyNotCommitted (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/write-batch.js:148:13)
at WriteBatch.update (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/write-batch.js:333:10)
at app.post (/user_code/exports/auth/user/startapp/initDefaultState.f.js:54:11)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at next (/user_code/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/user_code/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/user_code/node_modules/express/lib/router/layer.js:95:5)
at /user_code/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/user_code/node_modules/express/lib/router/index.js:335:12)
at next (/user_code/node_modules/express/lib/router/index.js:275:10)
Perhaps I'm missing something out in my code?
I resolved my problem. It was a silly mistake that I've made.
I had to declare batch inside app.post().
app.post('/', (req, res) => {
const batch = admin.firestore().batch();
});
Instead
module.exports = ({ admin, cors, express, functions }) => {
const app = express();
const fireStore = admin.firestore();
const rtdb = admin.database();
const apps = fireStore.collection('apps');
const users = fireStore.collection('users');
const batch = admin.firestore().batch();
};

Categories

Resources