I am trying to read the SQL query output in javascript
I am using Node.js , Express Engine (a MVC model) to read the MySQL database and display the output on UI using Jade.
I have a file index.js which fetches value of 'password' and 'user_name'from homepage.jade form field.
I have to check if the password entered by user matches the password in the database.
for which I am querying the database to get a matching record for the entered username and want to fetch the password value for that user and check if it is equal to the form value of password.
router.get('/sample', function(req, res) {
db=mysql.createConnection(config);
db.connect(function(err){
});
var formpass= req.body.password;
var user_name= req.body.userName;
var sql="select * from user where user_name= 'monicathaneer'";
db.query(sql, function(err_query,data)
{
for a in data
pass= a.password;
}
if(formpass==pass)
{
res.render('Login', {
"Login" : data });
}
});
I get errors saying unexpected token near 'a' and unexpected token near 'if' when I run the node.
I would like to know how can I can read the password property from the sql output in a .js file.
Your code sample has some syntax errors and lost curly braces. Try this (assuming you're using node-mysql module):
router.get('/sample', function(req, res) {
var formpass = req.body.password,
user_name = req.body.userName,
sql = "select * from user where user_name = 'monicathaneer'";
var db = mysql.createConnection(config);
db.connect(function (err) {
// you should handle the errors here
});
db.query(sql, function (err_query, data) {
// I'm assuming your query will return just 1 row
// because usernames should be unique
if (formpass === data[0].password) {
res.render(
'Login',
{"Login": data}); // In your context, 'data' contains the user password...
// Do you really want to send it back to the web page?
}
});
db.end(); // you forgot to close your connection.
});
Some considerations:
You should not try to handle authentication manually. Consider using a middleware like Passport.js;
You don't need to open and close your connection on each request. Try to refactor your code in order to open the connection when the app starts, and use it on demand.
Related
I'm just learning how to make a simple web-application for my dorm that would assign each participant a random number once they enter their name. There is a form field with one text box and a button. The text box (form) needs to send the full name (a single string) to the MySQL database so that later on I could retrieve the full list with the assigned numbers to actually use the application in the real world. Just for redundancy, I've put in code that creates a new database and a table every time, but then SQL ignores it if the DB and table already exist.
My fundamental problem is that I can not get data from my form in HTML. I'm using express.js and am trying to retrieve it, then post it into my database via the SQL module. Now as I'm a complete newbie, I have no idea how it should work. For the past 4 days, I've searched all over the internet to try to solve this issue. I don't know if the js document is the problem or the HTML document.
This is my HTML form (do tell me if you would need the whole thing):
<form action="/createPerson" method="POST">
<input type="text" name="name" value="Ime in priimek">
<input type="submit" name="name" value="Potrdi" class="gumbek">
</form>
And here is my complete node.js document:
var mysql = require('mysql');
var express = require("express");
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({
extended: false
});
const http = require('http');
var fs = require('fs');
const app = express();
const path = require('path');
const router = express.Router();
// Unique random number generator module
const uniqueRandom = require('unique-random');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
server = http.createServer(app);
server.listen();
// Start connecting to MySQL database
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "mydb"
});
//if database mydb exists, ignore database creation
let createMydb = "CREATE DATABASE if not exists mydb"
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(createMydb, function(err, result) {
if (err) throw err, console.log("Database already exists!");
console.log("Database OK (Already exists, will not create new one)");
});
});
//if table person exists, ignore table creation
let createTable = "CREATE TABLE if not exists person (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), number VARCHAR(255))";
var sql = createTable;
con.query(sql, function(err, result) {
if (err) throw err, console.log("Table exists, will not create new table");
console.log("Table OK (Already exists, will not create new one)");
console.log('Running at Port 3000');
console.log("Connected. Commencing value input into database.");
//var post = { name: req.body.name, number: random }
//app.get('/createPerson', urlencodedParser, function(err, req, res) {
if (err) throw err;
//res(req.body.name)
});
router.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
//__dirname : It will resolve to your project folder.
});
/*const random = uniqueRandom(1, 100);
const values = ['/createPerson', String(random())];
var insert = "INSERT INTO person (name, number) VALUES (?)"
con.query(insert, [values], function(err, result) {
if (err) throw err;
console.log("Value was inserted into database.");
});*/
app.get('/createPerson', function(req, res) {
res.render('form'); // if jade
// You should use one of line depending on type of frontend you are with
res.sendFile(__dirname + '/index.html'); //if html file is root directory
});
app.post('/createPerson', urlencodedParser, function(req, res) {
const random = uniqueRandom(1, 100);
const values = [String(req.body.name), String(random())];
var insert = "INSERT INTO person (name, number) VALUES (?)"
console.log(req.body.name);
con.query(insert, [values], function(err, result) {
if (err) throw err;
console.log("Value was inserted into database.");
res.sendFile(__dirname + '/numberAssigned.html');
res.end();
});
});
Now every time I press the button in the form, I get Cannot POST /createPerson inside the browser and no data was sent to my database. Browser (network tab) also gives me 404. Maybe it can't find the form?
I am a complete newbie at all of this, I can manage HTML and CSS, Javascript is something really new to me. If you find the time to help me, THANK YOU FROM THE BOTTOM OF MY HEART!
The problem is that you are using node.js http module and express at the same time.
You are setting up /createPerson within the express.js app, but starting the node.js http server instead. So, no end-points are present in the server you've started - hence 404 Page Not Found.
Usually, you use just one of them. Node.js http module provides an ability to start a low-level HTTP server. Express, on the other hand, is a more high-level solution for building http services. So in your case, I would stick with express and throw out http (express is using http module under the hood anyways).
But the fundamental problem of your solution is that it is too big and complex to bootstrap from scratch.
It could be really confusing to figure out what is going on in a complex app, since you are trying to do many things at once - express http server + sql database + html forms... Many things can go wrong, so better try a "Hello World" approach instead.
To debug a problem like that, I would downscale the app and try to check every little interaction level by level:
Level 1
Comment out http module usage and every mapping in express except POST for /createPerson
Make sure you run express app.listen() after the end-point setup.
Comment out all database access in /createPerson handler and leave just a log statement like that:
app.post('/createPerson', urlencodedParser, function(req, res) {
console.log(req.body.name);
}
Now run your script with node.js and try to check the POST on /createPerson with curl:
curl --data-urlencode "name=John Doe (Junior)" http://localhost:3000
(make sure you are using the right port)
Check node.js logs - you have to see a name you're sending with curl in there.
When you see the name in logs, Level 1 is complete!
Level 2
Now try to do the same POST, but form an HTML form.
Add a static mapping on /public to node.js.
Run the node.js server.
Open a page with the HTML form and POST it.
Make sure your form is sending data to correct URL and you see the data in node.js logs
Level 3
Only now, when you have data flowing from html to node.js, you can try to extend the system with a database. Reintegrate db access code back into /createPerson and debug the solution.
Good luck with the next levels!
I am building an application that has a backend that uses SQL queries to get data from a SQL Server database. However, I need to write a query that truncates and repopulates a table in that database using data from a second database. Here is what my code looks like:
// establishes a connection to serverName and uses DB1 as the database. But how can you access two?
global.config = {
user: 'username',
password: 'password',
server: 'serverName',
database: 'DB1'
};
// run this query. It's already been tested in SQL server and works fine there
let query = "TRUNCATE TABLE [DB1].[dbo].[Shop]; INSERT INTO [DB1].[dbo].[Shop] (Shop, shopDescription, Address, City)" +
" SELECT Shop, Description, Address, City FROM [DB2].[dbo].[ShopTable]"
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query(query) }).then(
result => {
console.log(result.recordset)
//result returns as "undefined"
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200);
sql.close();
}).catch(err => { //error is not thrown
res.status(500).send({ message: err})
sql.close();
});
I get an "undefined" result, and find that no update to the table was made. The issue here isn't exactly clear whether it can't reach the table in DB2, or if perhaps the command doesn't work with the Node.js mssql package?
It appears this was a front end to back end connection issue. I was able to get the query to work without any changes to the database information, so it appears I can access the second database without any issues.
component.ts
this.httpService.patch('update', {} ).subscribe()
index.js
app.patch('/api/update', controllers.manualQueries.update);
I have the following code
var user = function(req,res,next) {
db.findOne({ username: req.params.uid }, function (err, docs) {
//error handaling
if(err){console.log(err)}
//check if user is real
if(docs === null){
res.end('404 user not found');
}else{
//IMPORTANT PART res.sendFile(__dirname + '/frontend/user.html');
}
});
}
app.get('/user/:uid',user);
Don't worry about the database stuff.
I want to know how to get req.params.uid sent to the client side and how to get it from there.
Thanks so much.
If your user is configured correctly every request will have a user:
var user = function(req,res) {
db.User.findOne({ _id: req.user._id }, function (err, docs) {
//error handaling
if(err){console.log(err)}
//check if user is real
if(docs === null){
res.end('404 user not found');
}else{
res.json(docs)
}
});
and then your api endpoint is just '/user/
In your client just make a GET request to this endpoint (maybe using AJAX) and your response will be any user that makes that given request.
Note: You don't need to pass in next unless you are defining middleware.
This is just a more complete answer based on my comment.
If you want to store a string of information about the user with each request they make, then you want to use cookies.
When the user first makes a request to the page, you would set the cookie via the res.cookie. So, in your code, the final if statement would look something like:
if(docs === null) {
res.end('404 user not found');
} else {
res.cookie('uid', req.params.uid, { httpOnly: true });
//IMPORTANT PART res.sendFile(__dirname + '/frontend/user.html');
}
Then, in the next request, and futures requests before the cookie expires, you can access it using:
req.cookies.uid
However, you need the cookie-parser middleware somewhere in your app beforehand:
var cookieParser = require('cookie-parser');
app.use(cookieParser());
If you need to access the value of uid on the clientside, you could either use a template, or set the httpOnly value to false when setting it using res.cookie. Then you could access the cookie using document.cookies.
Check out this W3Schools page for accessing cookies on the clientside.
I'm in charge of setting up profile pages for each user. I have set up a way to route through to "../profile/:username", but I cannot figure out how to actually render a unique page for each user.
Here is my get from index.js
router.get('/profile/:userName', function (req, res) {
//find user object from database
var userName = req.params.userName;
var userObject = userlistdb.find({ username: userName });
//route through to the user's unique profile page
res.render('profile/' + userObject.username, { ObjectId: userObject._id});});
My profile.jade is pretty abysmal so I won't bother sharing.
Our app is connected to a remote Mongo database and as far as I can tell it's being called correctly. When I route through to a user page from our db, I get the error "Failed to lookup view "profile/undefined" in views directory". Because there is no /profile/[username].jade file for any user this isn't working.
How can I get around this issue? Do I need to create a new jade file for each user?
Thanks
You cannot render file profile/:userId as it doesn't exist, so
res.render('profile/' + userObject.username)
gonna throw exception, but what you can do is render profile_page for a specific user.
use callback on database calls,
create 2-3 views(error.jade, profile_not_found.jade, profile_page.jade)
And router should look like
router.get('/profile/:userName', function (req, res) {
//find user object from database
var userName = req.params.userName;
//findOne will return single user instance
userlistdb.findOne({username: userName}, function(err, user){
if(err){
//render some error page
//pass error, populate view, or just send InternalServerError(500)
res.render('error', {err: err});
} else if (!user){
//render 404 or more specific page
//pass not found username
res.render('profile_not_found', {username: username});
} else {
//render user page
//route through to the user's unique profile page
res.render('profile_page', {user: user}); //pass user, populate view
}
});
});
When i run my node.js script i get this error:
http://i.gyazo.com/4abc4f518db0de3cb36e34a9fa163e22.png
I was reading a similar error and the guy said it was because the script wasn't connecting to the mysql database. I've tried all of the different logins i can think of and it still wont work. I have tried connecting with no credentials and i get the same error. These are the current credentials i am using to log in:
host : 'localhost',
user : 'root',
password : 'mypassword',
database : 'milky',
The code where the error comes from:
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'maxitems\'', function(err, row, fields) {
if(offer.items_to_receive.length > row[0].value) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
offer.items_to_receive = [];
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'toomuch\',\'System\')', function(err, row, fields) {});
return;