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.
Related
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.
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.
i'm using Express to create a backend server using NodeJs. One of the functionalities of the project is to send and receive PDF files. The other routes of the backend send and receive JSON files but i want to create a route for send and receive PDF files, what can i do? What i have until now:
const express = require('express')
const app = express()
const db = require('./config/db')
const consign = require('consign')
const consts = require('./util/constants')
//const routes = require('./config/routes')
consign()
.include('./src/config/middlewares.js')
.then('./src/api')
.then('./src/config/routes.js') // my routes file
.into(app)
app.db = db // database using knex
app.listen(consts.server_port,()=>{
//console.log('Backend executando...')
console.log(`Backend executing at port: ${consts.server_port}`)
})
app.get('/',(req,res)=>{
res.status(200).send('Primary endpoint')
})
/* basically at routes.js file i'm handling http routes that manages JSON objects such as this one below:
*/
At routes.js:
// intercept http routes and pass specific funtion for handling them
module.exports =app=>{
app.route('/products')// regular JSON objects
.post(app.src.api.itensVenda.saveItem)
.get(app.src.api.itensVenda.getItems)
.put(app.src.api.itensVenda.toggleItemVisibility)
app.route('/articles')
.get(app.src.api.articles.getArticle)
.post(app.src.api.articles.saveArticle)
// the route above is the one that i want to use for sending and receive PDF files
app.route('/info')// ordinary JSON objects
.post(app.src.api.info.saveInfo)
.get(app.src.api.info.getInfo)
}
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.
Multer takes the files i upload and puts it inside the file object so we can access it through the file but then the req.body.image is empty and i want to be able to pass the file.originalname to the req.body.image as path to the stored disk location. Now, i am working with multiple file here so i want to store their paths in the req object and access it inside another middle ware.
I tried something like this
req.body.image.push(`path/${file.originalname}`)
which returns an error
TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
It looks like req.body.image isn't an Array but undefined when you're using push().
When multer adds a single file to the request object, it adds them to the req.file property. You can then access req.file in subsequent middleware like in the below example. If you have multiple uploaded files then you would access the File Array req.files and iterate through the collection to access each file object.
In your above code, you're modifying the req.body object and adding the property image, I wouldn't recommend changing the req.body object. It is good practice to not mutate things like the request headers or body. Instead, you can add a new property req.image to the request object.
The below example uses Router Middleware to encapsulate the upload logic, (which should be kept to a single route usually) and then adds that middleware to an Express Server.
imageUploadRouter.js
// imageUploadRouter.js
const router = require('express').Router()
const multer = require('multer')
const upload = multer({dest: 'uploads/'})
router.use(upload.single('image'))
router.use((req, res, next) => {
if (!Array.isArray(req.image)) {
req.image = []
}
if (req.file) {
req.image.push(`path/${req.file.originalName}`)
}
return next()
})
// add some additional routes for logic
router.post('/', (req, res) => {
// do something and respond
// you can access req.image here too
return res.sendStatus(201)
})
module.exports = router
server.js
// server.js
const express = require('express')
const ImageUploadRouter = require('./imageUploadRouter')
const server = new Express()
const port = process.env.PORT || 1337
server.use('/images', ImageUploadRouter)
server.listen(port, () => console.log(`Lisening on ${port}`))