I am a node.js and MySQL beginner and I just started setting up and trying out some basic code.
I find these two APIs to practice, one is the API for the CRUD database, and the other is the API for judging user login / registration.I tried to merge the APIs of these two files, and the result was a problem. I think the current problem is the configuration file (conf.js).I plan to write a function and then wrap any file and use it again, so that the configuration files may not conflict, but I don’t know how to start.
These are the two API teaching URLs I practiced
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
https://www.footmark.info/programming-language/nodejs/nodejs-restful-webapi-mysql/
index.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var authenticateController = require("./controllers/authenticate-controller");
var registerController = require("./controllers/register-controller");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/api/register", registerController.register);
app.post("/api/authenticate", authenticateController.authenticate);
app.listen(3000);
app.js
var bodyparser = require("body-parser");
var express = require("express");
var conf = require("./conf");
var functions = require("./functions");
var user = require("./routes/user");
var app = express();
req.body
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.use(functions.passwdCrypto);
app.use("/user", user);
app.listen(conf.port, function() {
console.log("app listening on port " + conf.port + "!");
});
authenticate-controller.js
var connection = require('./../conf');
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
if(password==results[0].password){
res.json({
status:true,
message:'successfully authenticated'
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
register-controller.js
var connection = require('../conf');
module.exports.register=function(req,res){
var today = new Date();
var user={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
});
}
user.js(models)
var mysql = require("mysql");
var conf = require("../conf");
var connection = mysql.createConnection(conf.db);
var sql = "";
module.exports = {
items: function(req, callback) {
sql = "SELECT * FROM user";
return connection.query(sql, callback);
},
item: function(req, callback) {
sql = mysql.format("SELECT * FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
add: function(req, callback) {
sql = mysql.format("INSERT INTO user SET ?", req.body);
return connection.query(sql, callback);
},
delete: function(req, callback) {
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
put: function(req, callback) {
connection.beginTransaction(function(err) {
if (err) throw err;
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
connection.query(sql, function(err, results, fields) {
if (results.affectedRows) {
req.body.id = req.params.id;
sql = mysql.format("INSERT INTO user SET ?", req.body);
connection.query(sql, function(err, results, fields) {
if (err) {
connection.rollback(function() {
callback(err, 400);
});
} else {
connection.commit(function(err) {
if (err) callback(err, 400);
callback(err, 200);
});
}
});
} else {
callback(err, 410);
}
});
});
},
patch: function(req, callback) {
sql = mysql.format("UPDATE user SET ? WHERE userId = ?", [req.body, req.params.id]);
return connection.query(sql, callback);
}
};
user.js(routes)
var express = require("express");
var user = require("../models/user");
var router = express.Router();
router
.route("/")
.get(function(req, res) {
user.items(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.post(function(req, res) {
user.add(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
res.status(201).json(results.insertId);
});
});
router
.route("/:id")
.get(function(req, res) {
user.item(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.delete(function(req, res) {
user.delete(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
res.sendStatus(204);
});
})
.put(function(req, res) {
user.put(req, function(err, results) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (results === 410) {
res.sendStatus(410);
return;
}
user.item(req, function(err, results, fields) {
res.json(results);
});
});
})
.patch(function(req, res) {
user.patch(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
req.body.id = req.params.id;
res.json([req.body]);
});
});
module.exports = router;
conf.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "farmbot",
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
/*If I comment out the code below, I can execute the login / register API*/
/*Without commenting out, can only perform CRUD on the database*/
module.exports = {
db: {
host: "localhost",
user: "root",
password: "1234",
database: "farmbot"
},
port: 3000
};
You will have to refactor them properly. You will need only once file to begin with. Why using it twice?
Refactor them in one file instead of listening to them on different ports. Once done, you can show the code to us so that we can fix it further if there's an issue.
Start from index.js and merge app.js with it but a bit carefully. I think doing it by yourself you will learn much from it.
I am new to Node js and express. I trying to query my Azure database to get the list of patients(MR number). I am getting the list but I think the request.on() runs as an asynchronous function so first, it will render the HTML page without any list and after executing the function Node Js exit executing.
Code:
var express = require('express');
var router = express.Router();
//For database
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
function mrquery(connection) {
request = new Request(
"SELECT DISTINCT MRNO FROM Transaction_Record",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
}
/* GET home page. */
router.get('/', async function(req, res, next) {
var connection = req.app.get('connection');
var isconnected = req.app.get('isconnected');
if (isconnected) {
mrquery(connection)
res.render('index', {
title: 'Express'
});
} else {
console.log('Not Connected');
res.render('error', {
error: 'error'
});
}
});
module.exports = router;
Thanks in advance.
I'm trying to add a delete image functionality to my website and even though my code deletes the file from the images folder and removes the image record from my database, I get an error in the console and I don't get redirected to my home page. The error is :
DeprecationWarning: Calling an asynchronous function without callback is deprecated.
And my code:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var fs = require('fs');
router.post('/', function(req, res, next) {
if (req.method == 'POST') {
var id = req.body.id;
var path = req.body.path;
var author = req.body.author;
var completePath = 'public/images/uploads/' + path;
db.query('DELETE FROM image WHERE id = ?', [id], function(error, results, fields) {
if (error) throw error;
if (fs.unlink(completePath)) {
console.log('Successful');
res.redirect('/');
} else {
console.log('Unsuccessful');
}
})
}
});
module.exports = router;
My console logs Unsuccessful and it doesn't redirect me to res.redirect('/');
fs.unlink is an asynchronous function that takes a callback on success. You should use it like this:
db.query('DELETE FROM image WHERE id = ?', [id], function(error, results, fields) {
if (error) throw error;
fs.unlink(completePath,function(err) {
if(err) {
console.log('unsuccessful');
return;
}
console.log('successful');
res.redirect('/');
});
})
I am trying to make a url shortener app using express. I have 2 middle wares for routes /shorten/:url* and /:code respectively. Somehow when I make requests like /shorten/iamarshad.com (requests that are not formatted and will fail my validateUrl method), middleware handling that request gets executed sometimes twice and sometime thrice. Why is this happening ?
Code for route.js:
var express = require("express");
var router = express.Router();
var crypto = require("./crypto");
var styles = "<style>#import url('https://fonts.googleapis.com/css?family=Cormorant+Garamond');" +
"body{background: #fefefe; word-wrap: break-word;}" +
"p {font-size: 30px;color: #b33c66;font-family: 'Cormorant Garamond', monospace;text-align: center;" +
"margin-top: 40vh;font-weight: 500;word-spacing: 2px;}</style>";
function verifyUrl(req, res, next) {
console.log("/shorten middleware called");
req.params.url += req.params[0];
console.log(req.params.url);
if (validateUrl(req.params.url)) {
req.db.collection("counter")
.find({_id: "counter"})
.toArray(function (err, docs) {
if (err) console.error("Error occurred while getting COUNTER document:", err);
req.encodedId = crypto.encode(docs[0].count);
next();
});
}
else {
var elem = "<p>Please enter correct and formatted url!</p>";
res.send(styles + elem);
}
}
function incrementCounter(req, res, next) {
// increasing counter
req.db.collection("counter")
.update(
{
_id: "counter"
},
{
$inc : {
count : 1
}
}
);
next();
}
function insertUrlDocument(req, res, next) {
//inserting new url document
var obj = {original_url: req.params.url, _id: req.encodedId, entry_time: new Date().toUTCString()};
req.db.collection("urls")
.insert(obj, function(err, data) {
if(err) console.error("Error happened while adding new document:", err);
});
next();
}
function sendResponse(req, res) {
var elem = "<p>" + JSON.stringify({'original_url': req.params.url, 'short_url': 'https://shorten-that.herokuapp.com/' + req.encodedId}) + "</p>";
res.send(styles + elem);
}
function validateUrl(url) {
var format = /(http:\/\/|https:\/\/)[a-z0-9\-]+[.]\w+/;
return (format.test(url));
}
router.get("/:code", function(req, res) {
console.log("/:code middleware called with url", req.params.code);
var code = req.params.code.toString();
// searching short-url-id
req.db.collection("urls")
.find({_id: code})
.toArray(function(err, docs) {
if(err) console.error("Error occurred while searching urls:", err);
console.log(docs);
if(docs.length > 0)
res.redirect(docs[0]["original_url"]);
else {
var elem = "<p>Oops, wrong url requested!</p>";
res.send(styles + elem);
}
});
});
// better solution needed
router.get("/shorten/:url*", [verifyUrl, incrementCounter, insertUrlDocument, sendResponse]);
module.exports = router;
Code for server.js:
var express = require("express")
, mongo = require("mongodb").MongoClient
, port = process.env.PORT || 8080
, path = require("path")
, routes = require("./routes")
, favicon = require("serve-favicon");
var app = express();
app.use(favicon(path.join(__dirname, 'public','favicon.png')));
app.use(express.static(path.join(__dirname, "public")));
var url = 'mongodb://localhost:27017/url-shortener';
mongo.connect(url, function(err, db) {
if (err) console.error("Error occurred while connecting to db:", err);
console.log("successfully connected to db.");
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
});
app.listen(port, function() {
console.log("App running on", port);
});
var express = require('express');
var search = express.Router();
search.get('/', function(req, res, next) {
console.log('1');
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
console.log('last');
next();
});
var dbCall = function(callback) {
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');
var bucket = cluster.openBucket('default');
var doc;
var ViewQuery = couchbase.ViewQuery;
var query = ViewQuery.from('dev_test', 'allData');
bucket.query(query, function(err, viewResults) {
if (err) {
callback(err, null);
} else {
console.log('inqueryCall');
var results = viewResults;
callback(null, results);
console.log(results);
}
});
};
module.exports = search;
Here's the error that I get is :
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
Can someone please explain the issue here(not just the solution)?
I've added console.log and the issue here is that the couchbase call to async
Remove next() call, that is causing this error. next() is used in middleware to pass the flow to next middleware or endpoint/route
search.get('/', function(req, res, next) {
dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});
});