Firebase REST get data - javascript

After watching Firebase Cloud Function Tutorial - REST API Part 1 | Diligent Dev, I have spent several hours trying to understand how to get the entire record that was posted into firestore. Here is index.js code:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const admin = require("firebase-admin");
admin.initializeApp();
const app = express();
app.use(cors({origin: true}));
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
res.status(201).send(JSON.stringify(user));
});
The JSON data I posted was:
{"id":123, "name":"Tony Stark", "email":"ironMan#MarvelComics.com"}
In this get, the id is returned but I can't seem to access the other properties that are part of the record (example name: Tony Stark)?
app.get("/:id", async (req, res) => {
const snapshot = await
admin.firestore().collection("users").doc(req.params.id).get();
const userId = snapshot.id;
const userData = snapshot.data():
constole.log(userData);
res.status(200).send(JSON.stringify({id: userId, ...userData}));
});
There must be a simple solution but console.log(userData) is not the answer! :-(
Almost forgot to say, my request from the browser is passing the user id as a query parameter, in this example localhost:5001/projectReference/user/1 and I also tried with the Cloud Firestore document id (.../user/XRAwtfj9FSubeCArvUtQ). In each case I see in the browser the JSON string {"id":"the_value_requested"} but no userData.

What does console.dir(userData) output? That should help you see what's in the returned object.
Are you confident that name and email are avtually present on the record in Firebase? It's possible your retrieval is working as expected but the data expected isn't there.

Related

Can someone copy my Firebase config data? [duplicate]

This question already has answers here:
Is it safe to expose Firebase apiKey to the public?
(10 answers)
Closed 11 months ago.
I use firebase for authentication on JS. Everything is making in client side. Anyone can look my js files, copy the config datas, can make own project. How can I hide that datas? Because my plan is "pay as you go", If anyone copy that data, i have a big trouble. What should I do?
Maybe Firebase REST API can solve my problem. Is there any example about authentication with REST API.
I tried move codes Node.js but I couldnt handle it.
You can see my index.js, It is on functions folder. I deploy it to firebase hosting.
Authentication doesnt work.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const express = require("express");
const config = require('./config.js');
const app = express();
admin.initializeApp(config);
const app2 = initializeApp(config);
const auth = getAuth();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
const mail=user.Email;
const pass=user.Password;
createUserWithEmailAndPassword(auth, mail, pass)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
});
exports.widgets = functions.https.onRequest(app);
You can ensure that your firebaseConfig is stored in an environment variable.
You can also secure the app with Firestore security rules and App Check

get data from internal JSON file

Hey i want to get the data from my json file and then display it in html, but first i will just console.log it. how do i exactly do that??
the json file will be updated as its the users input
varer.json
[{"id":"aa","varer":"aa","pris":""},{"id":"aa","varer":"aa","pris":""}]
varer-controller
const varerModel = require("./../models/varer");
const express = require("express");
const router = express.Router();
router.get("/getproducts", (req, res) =>{
var products = JSON.parse(varerModel)
console.log(products)
res.send(products)
})
You don't need to JSON.parse as it's already a JSON and can be directly used.

res.send() is not giving response on POST request in POSTMAN

hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.

Save JSON data from an API into a database and cache the request, so i won't need to request from the API again - Node.js / Express.js

I have this URL here: https://viacep.com.br/ws/01001000/json/ , that lets me retrieve JSON data whenever i change the given number on it(the number is unique). For example: 01001000 has its own data, and if i change it for 49140000, it will have its own data as well. What i want to do is: i want to save the JSON data into a database, and somehow cache/save the request, so if in the future i search for the same number again, it won't have to retrieve the data from the URL again.
I have this right now:
My city.routes.js where i make the request to the API:
const express = require('express');
const axios = require('axios');
const cityRouter = express.Router();
cityRouter.get('/:cep', async (request, response) => {
try {
const { cep } = request.params;
const resp = await axios.get(`https://viacep.com.br/ws/${cep}/json/`);
return response.json(resp.data);
} catch (error) {
return response.status(400);
}
});
module.exports = cityRouter;
An index.js to make easier to the server to import and use the routes:
const express = require('express');
const routes = express.Router();
const cityRoutes = require('./city.routes');
routes.use(cityRoutes);
module.exports = routes;
My server.js:
const express = require('express');
const routes = require('./routes');
const app = express();
app.use(express.json());
app.use(routes);
app.listen(3333, () => {
console.log('Server is on!');
});
I can retrieve the JSON data that i want without problems:
enter image description here
You can do this via using caching libraries or using db and indexing on based of number for faster retrieval.
My suggestion:
If you need to cache for smaller amount of time lets say week or so prefer caching libraries like redis or memcache.
There u can do something like:
await redis.set(key, JSON.stringify(data), { expiry: '1W'});
The above code varies depending on library you use. But the idea remains the same you cache the data with key(Number).
And next time before making request you first tries to get the key from cache provider.
await redis.get(key)
if above value is present you will get json string of the desired result and dont need to make the network call.
If not present you make the network call and cache the result for future use.
In case of DB approach you simply make a get request via key to the db.
But do index the key in collection or relation when initializing the structure for faster retrieval.

Trying to GET json data, getting "not a function" error

I'm creating a programmer job board app and I'm trying to display json data on my main page. At some point I'll render it, but for now I'm just trying to get it to show up in json form so that I know it works.
I'm able to connect to the server, but when I load the page I get a TypeError (Job.showAllJobs is not a function).
I'm using a crud app I made the other week as a reference, but there are a few differences between it and this project that are throwing me off.
Here's my project's file structure:
job-board
database
connection.js
schema.sql
models
Job.js
User.js
views
index.ejs
login.ejs
server.js
Unlike my previous crud app, this project is using a connection.js file that gave some trouble earlier. At first I thought I was out of the woods, but I think it might be responsible for my current problem.
Not getting GET to work might seem like a minor error, but it's really bugging me and I haven't been able to keep working because of it.
I populated my table (jobs) with a sample listing as a test, but in the very near future I plan on connecting the app to the GitHub jobs api.
server.js:
const express = require('express');
const app = express();
const PORT = 3000;
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const Job = require('./models/Job');
const User = require('./models/User');
const connection = require('./database/connection')
app.use(bodyParser.json())
app.use(methodOverride('_method'));
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.set("view engine", "ejs");
///// GET /////
// GET INDEX
app.get('/', (request, response) => {
Job.showAllJobs().then(everyJob => {
response.json('index');
// response.render('index', { jobs: everyJob });
});
});
Job.js
const Job = {};
const db = require('../database/connection');
///// JOBS /////
/// INDEX ///
Job.showAllJobs = () => {
return db.any('SELECT * FROM jobs');
};
module.exports = Job;
module.exports = db;
connection.js
// require database setup to use pg-Promise
const pgp = require('pg-promise')({});
// connection url
const connectionURL = "postgres://localhost:5432/job_board";
// new database connection
const db = pgp(connectionURL);
// module.exports = db;
You have a couple of problems here.
Make sure you're passing the jobs into res.json instead of the string 'index'
Make sure you're exporting db from connection.js
You're exporting both Job and db from Job.js. Since you're exporting db second, it's overriding the export of Job.

Categories

Resources