I have this code in routes/apiRoutes.js that gets employees from the database but I need to include the table name with it.
const express = require("express");
const router = express.Router();
const db = require("../models");
//get all
router.get("/all", (req, res) => {
db.employee.findAll().then((employees) => res.send(employees));
});
//post new
router.post("/new", (req, res) => {
db.employee
.create({
text: req.body.text,
})
.then((submitedemployee) => res.send(submitedemployee));
});
module.exports = router;
I did try to use MYSQL syntax but it doesn't work
var seq = new Sequelize('mysql://localhost/mysql');
seq.query('show tables').then(function(rows) {
console.log(JSON.stringify(rows));
});
Related
I'm learning reactjs and nodejs and with help of fellow stackoverflow members i've been able to successfully create the front end. Now i'm working on the back end in nodejs. Nodejs is also working fine but right now all my code is in single index.js file and i'm worried that its going to get bigger and bigger.
I just want to know how can I move stuff from index.js to seperate files ? For eg. I have catgeories (add,modify,delete list) then same for products, users etc.
My routes are like:
/add-category
/mod-category
/del-category
/categories
/add-user
/mod-user
/del-user
/users
/add-product
/mod-product
/del-product
/products
They're all working fine, just that they're in a single index.js file. How can I move routes of products into products.js and subsequently categories into categories.js and users into users.js ?
Some of my code is following as to how my index.js is:
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "shop",
});
app.get("/admin/categories", (req, res) => {
db.query("SELECT * FROM categories ORDER BY catg_name", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.put("/admin/mod-category", (req, res) => {
const id = req.body.id;
const name = req.body.name;
const description = req.body.description;
const status = req.body.status;
db.query(
"UPDATE categories SET catg_name = ?, catg_description = ?, catg_status = ? WHERE catg_id = ? LIMIT 1",
[name, description, status, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.delete("/admin/del-category/:id", (req, res) => {
const id = req.params.id;
db.query(
"DELETE FROM categories WHERE id = ? LIMIT 1",
[id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.listen(3001, () => {
console.log("Server is running on port 3001");
});
Any help is appericiated.
Thanks.
you can create a separate file for each collection.
categories routes file
const router = require('express').Router();
router.get('/categories/:id', (req, res) => {
// get a category by ID
});
router.post('/categories', () => {
// create a category
});
module.exports = router;
then a file for the products
const router = require('express').Router();
router.get('/products/:id', (req, res) => {
// get a product by id
});
router.post('/products', () => {
// create a product
});
module.exports = router;
after that import the exported routers to your index file and use them with
app.use() function
const express = require('express');
const productsRouter = require("./src/productsRouter");
const categoriesRouter = require("./src/categoriesRouter");
const app = express();
app.use(productsRouter);
app.use(categoriesRouter);
In this particular case, you can define each endpoint action as a file function.
You can do a categories.js file with any function that you need
const database = require('./connection.js')
const CATEGORIES = {
edit_categories : (req, res) => {
...
},
delete_categories : (req, res) => {
...
},
find_categories : (req, res) => {
...
}
}
module.exports = CATEGORIES
And apart you can define your connection.js
const mysql = require("mysql");
const database = () =>{
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "shop"
});
return db;
}
module.exports = database();
And then use it all
const express = require("express");
const app = express();
const cors = require("cors");
const CATEGORIES = require('./categories.js');
app.use(cors());
app.use(express.json());
app.get("/admin/categories", CATEGORIES.find_categories );
app.put("/admin/mod-category", CATEGORIES.edit_categories );
app.delete("/admin/del-category/:id", CATEGORIES.delete_categories );
app.listen(3001, () => {
console.log("Server is running on port http://127.0.0.1:3001");
});
Obviously there is some many different ways for structure your project (you can separate routes, modeling and views on that way)
I have set up my project to display posts from a MongoDB database. My localhost address is http://localhost:5000/api/posts and it displays my two saved posts. How can I add MongoDB _id to localhost adress to only display one post?
MongoDB _id: 6061890d59ec3b6abcb011fb
I have tried this:
http://localhost:5000/api/posts/6061890d59ec3b6abcb011fb
http://localhost:5000/api/posts/id:6061890d59ec3b6abcb011fb
http://localhost:5000/api/posts/_id:6061890d59ec3b6abcb011fb
All of them returns error Cannot GET /api/posts/and_the_above_parameters_for_each_example`
Index.js to connect my backend to my application.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
const posts = require("./routes/api/posts");
app.use("/api/posts", posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
posts.js to connect to MongoDB database. Below Password, MY_DATABASE and TABLE is changed to real values in my code.
const express = require("express");
const mongodb = require("mongodb");
const router = express.Router();
//Get posts
router.get("/", async (req, res) => {
const posts = await loadPostCollection();
res.send(await posts.find({}).toArray());
});
//Add post
router.post("/", async (req, res) => {
const posts = await loadPostCollection();
await posts.insertOne({
text: req.body.text,
createdAt: new Date(),
});
res.status(201).send();
});
router.delete("/:id", async (req, res) => {
const posts = await loadPostCollection();
await posts.deleteOne({
_id: req.params.id,
});
res.status(200).send();
});
async function loadPostCollection() {
const client = await mongodb.MongoClient.connect(
"mongodb+srv://MongoDB:PASSWORD#cluster0.5pnzd.mongodb.net/MY_DATABASE?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
return client.db("MY_DATABASE").collection("TABLE");
}
module.exports = router;
PostService.js to display posts on localhost and methods to post and delete.
import axios from "axios";
const url = "http://localhost:5000/api/posts/";
class PostService {
// Get posts
static getPosts() {
return new Promise((resolve, reject) => {
axios
.get(url)
.then((res) => {
const data = res.data;
resolve(
data.map((post) => ({
...post, //spread operator
createdAt: new Date(post.createdAt),
}))
);
})
.catch((err) => {
reject(err);
});
});
}
// Create posts
static insertPost(text) {
return axios.post(url, {
text,
});
}
static deletePost(id) {
return axios.delete(`${url}${id}`);
}
}
export default PostService;
router.get("/:id", async (req, res) => {
const posts = await loadPostCollection();
res.send(await posts.findOne({
_id: req.params.id,
}));
});
Number 1: http://localhost:5000/api/posts/6061890d59ec3b6abcb011fb is correct, but you're going to need to create a new route to handle that request.
These are often called 'show' routes.
router.get("/:id", async (req, res) => {
// code to handle the logic of that request
// access the url parameter via: req.params.id
});
This is an express server that interacts with a mongoDb server using mongoose.Here I want to search for a specific entry with a given name instead of using findbyid function in the /getCollege/:name route.
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// app.use(parser);
mongoose.connect('mongodb+srv://swapnil:abc#cluster0.ma46p.mongodb.net/db?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('connected to db') })
//
app.get('/', (req, res) => {
res.send('We are home');
})
app.get('/getCollege/:name',async (req,res) =>{
})
app.listen(3000);
Parameters variables such as :name are available through req.params, on your case: req.params.name. After getting the value you would something like:
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// your code
app.get('/getCollege/:name',async (req, res) =>{
try {
const document = await College.findOne({ name: req.params.name });
res.json(document);
} catch(error) {
// Handle the error here.
console.log(error);
}
});
// your code
Take a look at these reading materials as well:
1 - http://expressjs.com/en/guide/routing.html
2 - https://medium.com/weekly-webtips/9-best-practices-for-rest-api-design-7fb0b462099b
I'm taking a course on NodeJS, there were a few assignments related to routing, everything works fine except this part which seems a little odd: For some reason, I cannot read the parameter ID being passed to the mounted router.
dish.js
const express = require('express');
const bodyParser = require('body-parser');
const dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.all((req,res,next) => {
res.statusCode = 200;
res.setHeader('Content-Type','text/plain');
next();
})
.get((req,res) => {
console.info('Info: ',req);
res.end(`Sending details of the dish back to you: ${req.params.dishId}`);
})
.post((req,res) => {
res.statusCode = 403;
res.end(`Operation not supported: ${req.params.dishId}`);
})
.put((req,res) => {
res.write(`Updating the dish...: ${req.params.dishId} \n` );
res.end(`Will update this dish: ${req.body.name} with details: ${req.body.description}`);
})
.delete((req,res) => {
res.end(`Deleting this dish: ${req.params.dishId}`);
});
exports.dish = dishRouter;
dishes.js
const express = require('express');
const bodyParser = require('body-parser');
const dishesRouter = express.Router();
dishesRouter.use(bodyParser.json());
dishesRouter.route('/')
.all((req,res,next) => {
res.statusCode = 200;
res.setHeader('Content-Type','text/plain');
next();
})
.get((req,res) => {
res.end('Sending all dishes back to you');
})
.post((req,res) => {
res.end(`Will add the dish: ${req.body.name} with details: ${req.body.description}`);
})
.put((req,res) => {
res.statusCode = 403;
res.end(`Operation not supported.`);
})
.delete((req,res) => {
res.end(`Deleting all dishes.....`);
});
exports.dishes = dishesRouter;
index.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const http = require('http');
const dishRouter = require('./routes/dish');
const dishesRouter = require('./routes/dishes');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use('/dishes',dishesRouter.dishes);
app.use('/dishes/:dishId',dishRouter.dish);
app.use(express.static(__dirname+'/public'));
app.use((req,res,next) => {
res.statusCode = 200;
res.setHeader('Content-Type','text/html');
res.end('<html><body><h1>This is an Express Server</h1></body></html>');
});
const server = http.createServer(app);
server.listen(port,hostname,(req,res) => {
console.info(`Server running on port: ${port}, at: ${hostname}`);
})
This GET localhost:3000/dishes/123 is calling the right route, but the parameter dishId comes back as "undefined". Again, just learning nodeJS, seems like my receiver/mounted route should receive those parameters just fine, the body can be read properly, but not the params. ... thanks.
Yeah the params don't flow between routers. You're on a new router, hence new route params object.
You can check out the code for this:
https://github.com/expressjs/express/blob/master/lib/router/index.js#L43
Check out line 43 and line 53 where route.params is set to an empty object.
Some examples:
index.js
app.use('/dishes/:dishId',(req, res) => {
console.log('now I get my dishId', req.params.dishId)
});
dish.js (version 1)
dishRouter.route('/')
.get((req, res) => {
console.log('now i get nothing', req.params)
})
dish.js (version 2)
dishRouter.route('/:anotherId')
.get((req, res) => {
console.log('now we get another parameter', req.params.anotherId)
})
// the path would be /dish/123/456
I'm not sure if there is a offical-expressjs-way to pass the params object between routers.
One solution would be to create a custom handler
index.js
app.use('/dishes/:dishId', handler)
handler.js
function handler (req, res, next) {
if (req.method === 'GET') {
console.log('now we get it', req.params)
}
}
module.exports = handler
Anoter way would be to add the dishId to the request object before calling the router:
index.js
app.use('/dishes/:dishId', (req, res, next) => {
req.dishId = req.params.dishId
router(req, res, next)
})
dish.js
const express = require('express')
const router = express.Router()
router.route('/')
.get((req, res) => {
console.log('nothing here', req.params)
console.log('dishId', req.dishId)
})
module.exports = router
Third way would be to send the params as options to a router function
index.js
app.use('/dishes/:dishId', (req, res, next) => {
router(req.params)(req, res, next)
})
dish.js
function createRouter (options) {
const router = express.Router()
router.route('/')
.get((req, res) => {
console.log('nothing here', req.params)
console.log('but alot here', options)
})
return router
}
module.exports = createRouter
If you want you could also just put the :dishId on the router as an optional parameter
index.js
app.use('/dishes', dishesRouter)
dishes.js
const express = require('express')
const router = express.Router()
router.route('/:dishId?')
.get((req, res) => {
if (req.params.dishId) {
res.end(`Sending details of the dish back to you: ${req.params.dishId}`)
} else {
res.end('Sending all dishes back to you');
}
})
module.exports = router
I'm a beginner for NodeJS. For login functionality implement I needed to Set Up Passport to Handle the Express Authentication.
Here is my index.js
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const path = require ('path');
//const passport = require ('passport');
const {mongoose} = require ('./db.js');
var employeeController = require('./controllers/employeeController.js');
var reservationController = require('./controllers/reservationController.js');
var app = express();
app.use(bodyParser.json());
app.use(cors({origin: 'http://localhost:4200'}));
app.listen(3000, () => console.log('server started at port :3000'));
app.use('/employees',employeeController);
app.use('/reservations',reservationController);
Here I commented out passport
This is my employee controller which retrieve data
const express = require ('express');
var router= express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var {Employee} = require('../models/employee');
// =>localhost:3000/employees
router.get('/',(req,res) => {
Employee.find((err,docs) => {
if(!err) {res.send(docs);}
else {console.log('error in retrieving employees :' + JSON.stringify(err,undefined,2)); }
});
});
router.get('/:id',(req,res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
Employee.findById(req.params.id,(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in retriving employee:'+JSON.stringify(err,undefined,2));}
});
});
router.post('/',(req,res) =>{
console.log(req.body);
var emp = new Employee ({
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
});
emp.save((err,doc) => {
if(!err) {res.send(doc);}
else{console.log('error in saving employee'+ JSON.stringify(err,undefined,2));}
});
});
router.put('/:id', (req, res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
var emp = {
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
};
Employee.findByIdAndUpdate(req.params.id,{$set:emp},{new:true},(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in updating employee:'+JSON.stringify(err,undefined,2));}
});
});
router.delete('/:id',(req,res)=>{
if(!ObjectId.isValid(req.params.id))
return res.status(400).send('No record with given id : ${req.params.id}');
Employee.findByIdAndRemove(req.params.id,(err,doc) =>{
if(!err){res.send(doc);}
else{console.log('error in deleting employee:'+JSON.stringify(err,undefined,2));}
});
});
module.exports = router;
My app is retrieving data from the mongodb perfectly. But when I remove the comment out of the passport in the index.js data retrieval not happen. I can't figure out what's went wrong when I add passport.
Please help me as I'm new one for NodeJS.
passport is not a middleware.
const path = require ('path');
const passport = require ('passport');
....
app.use(passport.initialize())
.... //your routes
Hope this solves your issue