I am learning nodejs and I created few API when I have my all functionality in server.js it is working properly.
Now when I separated my code in dbConfig.js, server.js, and in ProductController.js. I started receiving 404, but my DB connection is working fine.
server.js:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const conn = require('./connection/dbConfig');
const productRouter = require('./controller/ProductController');
// parse application/json
app.use(bodyParser.json());
//Server listening
app.listen(3000,() =>{
console.log('Server started on port 3000...');
});
And my ProductController.js:
'user strict';
const conn = require('../connection/dbConfig');
const express = require('express');
const app = express();
//show all products
app.get('/getAllProducts',(req, res) => {
let sql = "SELECT * FROM product";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//show single product
app.get('/getProductById/:id',(req, res) => {
let sql = "SELECT * FROM product WHERE product_id="+req.params.id;
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//add new product
app.post('/addProduct',(req, res) => {
let data = {product_name: req.body.product_name, product_price: req.body.product_price};
let sql = "INSERT INTO product SET ?";
let query = conn.query(sql, data,(err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});