[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
app.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
app.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));
Describe the bug
I am trying to send form data to my API but req.body is undefined for some reason.
To Reproduce
Steps to reproduce the behavior:
create a new request
enter your API endpoint URL
select the body tab and then select the form-data tab
enter the key name of the form data you are trying to send so your API can recognize it and then the value.
Click send and you should get a response with a status code of 200. If you get an error like me telling me that req.body is undefined then you have the same problem as me.
You are using bodyparser.json(). From the documentation, this will parse requests that are only in JSON. You are better off using bodyParser.urlencoded([options]).
I advise using express.urlencoded instead.
Read this for clarification
you are missing the router
[ server.js ]
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);
const connection = mysql.createConnection({
host: conf.host,
user: conf.user,
password: conf.password,
port: conf.port,
database: conf.database
});
connection.connect();
// u need a router
const router = express.Router();
router.get("/api/users", (req, res) => {
connection.query(
"select * from users where isDeleted = 0",
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
}
);
});
router.post("/api/users", (req, res) => {
let sql = "insert into users values (null,?,?,now(),now(),0)";
let name = req.body.name;
let dsc = req.body.dsc;
let params = [name, dsc];
console.log(params);
connection.query(sql, params,
(err, rows, fields) => {
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
router.delete("/api/users/:id", (req, res) => {
let sql = "update users set isDeleted = 1 where id = ?";
let params =[req.params.id];
connection.query(sql,params,
(err, rows, fields)=>{
res.send(rows);
// console.log(err);
// console.log(rows);
});
});
app.use(router);
app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));
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 this procedure xyz_users_list and it return list of users with exec xyz_users_list but how do i use it in nodejs app?
Code
index.js
'use strict';
const express = require('express');
const app = express();
const mysql = require('mysql');
var connection = require('express-myconnection');
require('dotenv').config();
app.use(
connection(mysql, {
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
}, 'request')
);
app.get('/', (req, res) => {
return res.sendFile(__dirname + '/index.html');
});
//all users
var Users = require('./routes/Users');
app.get('/users', Users.list);
Users.js
'use strict';
var response = require('../res');
const { exec } = require('child_process');
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query(exec('xyz_users_list'), function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
this code returns:
TypeError: Cannot read property 'query' of undefined
If I use code below it works just fine but since i want to use exec it's returning error.
exports.list = function(req, res) {
req.getConnection(function(err, connection) {
connection.query('SELECT * FROM `users`', function(err, rows) {
if (err)
console.log("%s ", err);
response.success(rows, res);
});
});
};
any idea?
Update
here is result of my exec xyz_users_list in SQLQuery
Your connection is coming as undefined so it is showing this error. Try this version
const sql = require("mssql");
exports.list = async function(req, res) {
const connection = await sql.connect("connectionString");
const results = await connection.request().execute("xyz_users_list");
}
Need to add the corresponding return statements but you will get an idea.
I have multiple routes setup. I want to get specific data from another route. That data is coming from a post method.
My server.js look like this:
var mysql = require('mysql')
var morgan = require('morgan')
var cors = require('cors')
var bodyParser = require('body-parser')
var http = require('http')
var dateFormat = require('dateformat')
const port = process.env.PORT || 3000;
//middleware
var app = express()
app.use(cors())
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
var now = new Date()
//routes
var user_details = require('./routes/users')
var user_orders = require('./routes/order')
//Use routes
app.use('/', user_details)
app.use('/', user_orders)
//Launch Server
app.listen(port, () => {
console.log('Server start at port: ' + port)
})
My routes/users.js :
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
router.post('/list', (req, res) => {
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_' + appendRandomString
var email = req.body.email
var listItems = req.body.listItems
var listTitle = req.body.listTitle
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
const INSERT_USER_LISTS = `INSERT INTO user_lists (id,date,time,user_email,list_title,list_items) VALUES('${id}','${date}','${time}','${email}','${listTitle}','${listItems}')`
db.query(INSERT_USER_LISTS, (err, success) => {
if (err) {
return res.send(err)
} else {
console.log('list added')
res.send('list added')
}
})
})
module.exports = router
And my routes/order.js
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
var user_details = require('./users')
router.post('/sendOrder', (req, res) => {
var email = req.body.email
var status = 'Order Confirmed'
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_ORDER_' + appendRandomString
var list_items = ''
var list_title = ''
var data = {
id: id,
email: email,
list_items: list_items,
list_title: list_title,
date: date,
time: time,
status: status
}
const CREATE_ORDER = `INSERT INTO user_orders SET ?`
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err)
} else {
res.send('oc')
}
})
})
module.exports = router
I want the list_items and list_title in my order.js from users.js , this two data is coming from a POST method as you can see in users.js
If I understood you correctly you want to use request body which comes to /users in another route /orders.
You are saving user data list_title and list_item in users table. So all you need to access the data from /orders route is make an additional query to db where you will select users by id\email.
Not sure which db ORM you use but in general cases your code may look like this:
router.post('/sendOrder', async (req, res) => {
const { email } = req.body;
// declare other fields
const user = await db.query(
`SELECT * FROM users WHERE email LIKE '%${email}%'`,
(err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
}
);
// declare `data` object with user.list_title, user.list_item
const CREATE_ORDER = `INSERT INTO user_orders SET ?`;
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
});
});
I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!
I'm passing a data of a variable in URl from an python as
response = urlopen("localhost:5000/warehouse?fruitid=103456",timeout=10);
data = json.loads(response.read().decode('utf8'));
And it reading the response in json format for further processing.
How can I write the node.js routing for posting the data which reads the passed variable value of fruitid=103456 and insert the timestamp into the database when this request occurs.
Please help me out__...
try this - i use this to parse out json responses from other sources...
import pandas as pd
data1=dict(field1=data['field1_in_response'], field2=data['field2_in_response'],...);
data1=pd.DataFrame(data1)
print(data1)
const express = require('express');
const app = express();
const port = 5000;
var mysql = require('mysql')
var squel = require("squel");
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'toor',
database: 'invoice'
});
app.get('/warehouse', (req, res) => {
let fruitid = req.query.fruitid;
let queryDashboard = "select * from fruit where fruitid ='"+fruitid +"'";
connection.query(queryDashboard, function (err, rows, fields) {
if (err) throw err
console.log('query get successful');
var result = rows.map(data => data.name);
res.send(result);
// connection.end()
})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));`enter code here`
Here's how you could handle this kind of request in an Express/MongoDB app:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const port = 5000;
app.get('/warehouse', (req, res) => {
console.log('fruitid:', req.query.fruitid);
MongoClient.connect('mongodb://localhost:27017', function (err, client) {
if (err) throw err;
const db = client.db('mydatabase');
db.collection('fruits').find({ id: req.query.fruitid }).toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));