How do you nest routes in express? - javascript

I am new to express and node and I have this situation:
controller:
exports.find_by_IDN_post = (req, res) => {
console.log('init')
accidentDetail.findOne({ idn: req.body.idn }, (err, data) => {
if (err) {
res.status(500).send(err)
}
console.log(data)
res.status(200).send(data)
})
}
exports.find_by_name_post = (req, res) => {
accidentDetail.findOne({$or: [{'firstName': req.body.name}, {'middleName': req.body.name}, {'surname': req.body.name}]}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
exports.find_by_date_post = (req, res) => {
accidentDetail.findOne({firstReg: req.body.firstReg}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
exports.find_by_accident_type_post = (req,res) => {
accidentDetail.findOne({accidentType: req.body.accidentType}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
route:
const express = require('express')
const router = express.Router()
const query_controller = require('../controllers/QueryController')
router.post('/idn', query_controller.find_by_IDN_post)
router.post('/name', query_controller.find_by_name_post)
router.post('/date', query_controller.find_by_date_post)
router.post('/accidentType', query_controller.find_by_accident_type_post)
module.exports = router
app
const queryRouter = require('./routes/query')
app.use('/query', queryRouter)
How do I nest the routes? I want to be able to access the routes like this:
localhost:3001/query/idn
localhost:3001/query/name
...
At the moment, I can't receive the console.log('init') when trying to access localhost:3001/query/idn.

Related

Middleware is breaking redis / express setup

I'm using redis for the first time, and I can't quite figure out why my middleware 'cache' function is breaking my code? It works great without it, displays in the browser, if I go to my terminal and check for a key value pair it works great.
Here is my setup:
const express = require("express");
const redis = require("redis");
const axios = require("axios").default;
const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.PORT || 6379;
const client = redis.createClient(REDIS_PORT);
client.connect();
const app = express();
function setResponse(username, repos) {
return `<h2>${username} has ${repos} Github repos</h2>`;
}
// make req to github
async function getRepos(req, res, next) {
try {
console.log("fetching data...");
const { username } = req.params;
const response = await axios.get(
`https://api.github.com/users/${username}`
);
const data = response.data;
const repos = data.public_repos;
// set to redis
client.set(username, repos);
res.send(setResponse(username, repos));
} catch (err) {
console.log(err);
res.status(500);
}
}
// Cache middleware
function cache(req, res, next) {
const { username } = req.params;
client.get(username, (err, data) => {
if (err) throw err;
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
});
}
app.get("/repos/:username", cache, getRepos);
app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});
Any advice would be much appreciated!
Your cache function
function cache(req, res, next) {
const { username } = req.params;
client.get(username, (err, data) => {
if (err) throw err;
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
});
}
uses node redis 3 "logic" so it's hanging
redis 4 is promise led, so you need to use async/await or .then/.catch
So something like this should work for the .then/.catch approach
// Cache middleware
function cache(req, res, next) {
console.log('caching for', req.params);
const { username } = req.params;
client.get(username)
.then((data) => {
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
})
.catch(err => {
if (err) throw err;
});
}
This will solve your initial problem of "why it's getting stuck"

TypeError: signin.handleSignin is not a function

I"ve seen this question asked before, but I cannot quite figure out what it is I'm doing wrong. I have an endpoint: app.post('/signin', signin.handleSignin(db, bcrypt)) in my server.js file. The console is alerting me that signin.handleSignIn is not a function. This endpoint is linked to a file in my controllers folder that is signin.js that looks like this:
const handleSignin = (db, bcrypt) => (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json('incorrect form submission');
}
db.select('email', 'hash').from('login')
.where('email', '=', email)
.then(data => {
const isValid = bcrypt.compareSync(password, data[0].hash);
if (isValid) {
return db.select('*').from('users')
.where('email', '=', email)
.then(user => {
res.json(user[0])
})
.catch(err => res.status(400).json('unable to get user'))
} else {
res.status(400).json('wrong credentials')
}
})
.catch(err => res.status(400).json('wrong credentials'))
}`enter code here`
export default handleSignin;
server.js code:
import express, { application, response } from "express";
import bcrypt, { hash } from "bcrypt-nodejs";
import cors from "cors";
import knex from "knex";
import signin from "./controllers/signin.js"
const db = knex({
client: "pg",
connection: {
host: "127.0.0.1",
port: 5432,
user: "postgres",
password: "test",
database: "smart-brain",
},
});
db.select("*")
.from("users")
.then((data) => {});
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.get("/", (req, resp) => {
resp.send(db.users);
});
app.post('/signin', signin.handleSignin(db, bcrypt))
app.post("/signin", (req, resp) => {
db.select("email", "hash")
.from("login")
.where("email", "=", req.body.email)
.then((data) => {
const isValid = bcrypt.compareSync(req.body.password, data[0].hash);
if (isValid) {
return db
.select("*")
.from("users")
.where("email", "=", req.body.email)
.then((user) => {
console.log(user);
resp.json(user[0]);
})
.catch((err) => resp.status(400).json("Unable to get user"));
} else {
resp.status(400).json("Wrong credentials");
}
})
.catch((err) => resp.status(400).json("Wrong credentials"));
});
app.post("/register", (req, resp) => {
const { name, email, password } = req.body;
const hash = bcrypt.hashSync(password);
db.transaction((trx) => {
trx
.insert({
hash: hash,
email: email,
})
.into("login")
.returning("email")
.then((loginemail) => {
trx("users")
.returning("*")
.insert({
name: name,
email: loginemail[0],
joined: new Date(),
})
.then((user) => {
resp.json(user[0]);
});
})
.then(trx.commit)
.catch(trx.rollback);
}).catch((err) => resp.status(400).json("unable to register"));
// bcrypt.hash(password, null, null, function (err, hash) {
// console.log(hash);
// });
});
app.get("/profile/:id", (req, resp) => {
const { id } = req.params;
db.select("*")
.from("users")
.where({ id })
.then((user) => {
if (user.length) {
resp.json(user[0]);
} else {
resp.status(400).json("Not found");
}
})
.catch((err) => resp.status(400).json("Error getting user"));
// if (!found) {
// resp.status(400).json("not found");
// }
});
app.put("/image", (req, resp) => {
const { id } = req.body;
db("users")
.where("id", "=", id)
.increment("entries", 1)
.returning("entries")
.then((entries) => {
resp.json(entries[0]);
})
.catch((err) => resp.status(400).json("Unable to get entries"));
});
app.listen(3001, () => {
console.log("App is running at port 3001");
});
You didn't exported signin from signin.js, you exported handleSignin.
so just import handleSignin and call it directly.
import handleSignin from "./controllers/signin.js"
...
app.post('/signin', handleSignin(db, bcrypt))

unable to call and manipulate external api in node js using request

I am trying to call [https://jsonplaceholder.typicode.com/albums/1/photos] in my node codes so that i create an end-point that is dynamic...like if i change 1 in url i get the relevant photos.
here are my codes
const request = require('request');
const callExtrenalApiUsingRequest = async (callback, req, res) => {
try {
let id = req.params.id
await request(`https://jsonplaceholder.typicode.com/albums/${id}/photos`, { json: true }, (err, res, body) => {
if (err) {
return callback(err);
}
return callback(body)
})
}
catch (error){
console.log(error)
}
}
module.exports.callApi = callExtrenalApiUsingRequest;
request.js
const apiCallFromRequest = require( './request.js');
const http = require('http')
http.createServer((req, res) => {
try {
if (req.url === "/request/photos/:id") {
apiCallFromRequest.callApi(function (response) {
res.write(JSON.stringify(response));
res.end();
})
}
}
catch (err) {
console.log(err)
}
}).listen(3000)
console.log("service running on port 3000...")

NodeJS pass Array from MongoDB to EJS file

i'm trying to make an option tag for every item which is in my Array in MongoDB. I have tried some ways but EJS throws me everytime the same error "gate is not defined"..
Here is my function in my route:
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});
And this is my EJS function:
<select id="torauswahl" name="torauswahl" style="padding:10px;font-size: large; width: 300px">
<% for (var i = 0; i < gate.length; i++){%>
<option value="<%=gate[i]%>"><%=gate[i]%></option>
<%}%>
</select>
thats my full JS file for understanding the logic:
const express = require('express');
const router = express.Router();
// Load Buchung model
const Buchung = require('../DB/models/Buchung');
const User = require('../DB/models/User');
const Tor = require(('../DB/models/Tor'));
const { ensureAuthenticated } = require('../DB/config/auth');
const passport = require('passport');
//Startseite Breuninger
router.get ('/startseite_breuninger', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_breuninger',{
vorname: req.user.vorname,
buchungen: buchungen || []
});
});
});
//startseite Spedi
router.get ('/startseite_spediteur', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_spediteur',{
buchungen: buchungen || []
});
});
});
//Buhchungsübersicht mitarbeiter
router.get('/buchungsuebersicht', (req, res) => res.render('buchungsuebersicht'));
//Buhchungsübersicht spedi
router.get('/neueBuchung_spediteur', (req, res) => res.render('neueBuchung_spediteur'));
//torauswahl spedi
router.get ('/torauswahl', (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('torauswahl',{
buchungen: buchungen || []
});
});
});
//torverwaltung mitarbeiter
router.get ('/torverwaltung', (req, res) =>{
Tor.find(function (err, tor) {
if (err)
return res.send(err);
res.render('torverwaltung',{
tor: tor || [],
});
});
});
//Update Benutzerdaten Breuni
router.post('/update_detailansicht_breuninger',(req,res) =>{
const username = req.body.username;
const telefon = req.body.telefon;
const email = req.body.email;
User.update({username: username}, telefon);
res.render('detailansicht_breuninger');
});
//insert
//insert
router.post('/neueBuchung_spediteur',ensureAuthenticated,(req, res) => {
const {sendungsstruktur, datepicker, timepicker1, timepicker2, sendungen, EUP, EWP, pakete, bemerkung, teile } = req.body;
var user = req.user;
if (errors.length > 0) {
User.findOne({ username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user));
if (err) { throw err; }
if (user) {
res.render('neueBuchung_spediteur', {
gate: user.gate || []
});
}
});
}
const newBuchung = new Buchung({
sendungsstruktur,
datepicker,
timepicker1,
timepicker2,
sendungen,
EUP,
EWP,
pakete,
bemerkung,
teile
});
newBuchung.save()
.then(buchung =>{
res.send('saved')
})
.catch(err=>console.log(err));
console.log(newBuchung)
});
router.post(
'/login',
passport.authenticate('local', {
failureRedirect: '/login'
}), (req, res) => {
if (req.user.admin == "spediteur") {
res.redirect('/buchungen/startseite_spediteur');
} else {
res.redirect('/buchungen/startseite_breuninger');
}
});
module.exports = router;
Im thankful for any help :)
I think the issue is that req.user is undefined. Can you try logging req.user during your route function?
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user))
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});

promises exercise in JS

I'm training on JS promises with a short URL generator exercise and I'm stuck. The console sends me back: Resultat: undefined.
I need help please !
import express from 'express';
import shortUrl from 'node-url-shortener';
const router = express.Router();
router.get('/', (req, res) => {
res.render('postUrl');
})
router.post('/test', (req, res) => {
const getShortUrl = () => {
return new Promise((resolve, reject) => {
const test = shortUrl.short('https://google.com', (err, url) => {
return url;
});
resolve(test)
})
}
getShortUrl()
.then((result) => {
console.log('Resultat : ' + result)
})
.catch((err) => {
console.log('Error : ' + err)
})
res.render('getShortUrl');
})
export { router }
Just move result(test) to inside the callback. Like this:
import express from 'express';
import shortUrl from 'node-url-shortener';
const router = express.Router();
router.get('/', (req, res) => {
res.render('postUrl');
})
router.post('/test', (req, res) => {
const getShortUrl = () => {
return new Promise((resolve, reject) => {
shortUrl.short('https://google.com', (err, url) => {
resolve(url);
});
})
}
getShortUrl()
.then((result) => {
console.log('Resultat : ' + result)
})
.catch((err) => {
console.log('Error : ' + err)
})
res.render('getShortUrl');
})
export { router }

Categories