Nodejs: Post method url body parser shows undefined - mysql

I want to use url post params to execute mysql query. I am getting error during mysql command when I post through postman. I dont know what is problem with this code. Here is my code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var md5 = require('MD5');
var con = mysql.createConnection({
host: "localhost",
user: "shoaib",
password: "",
database: "watch"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.post('/',function(req, res) {
con.connect(function(err) {
var query = "Select * From user Where email=? AND password=?";
var table = [req.body.email,req.body.password ];
console.log(req.body);
query = mysql.format(query, table);
con.query(query, function (err, rows) {
if (err) {
res.json({ "Error": true, "Message": "Error executing MySQL query" });
} else if(rows!=0) {
res.json({ "Error": false, "Message": "Success","Users": rows });
} else {
res.json({ "Error": true,});
}
});
});
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
Node is working perfectly but when I execute command url I face error.

Make sure on your request that you set the Content-Type header to application/json or application/x-www-form-urlencoded since your app supports either. Without a Content-Type header with either of these values body-parser will not read the request body and res.body will be undefined.
Example POST Request with Content-Type: application/json
const {request} = require('http')
const requestBody = {email: 'abc#gmail.com', password: 'abcdef123456'}
const jsonPostRequest = request({
method: 'POST',
host: 'localhost',
port: 8080,
path: '/api/',
headers: {'Content-Type': 'application/json'}
}, res => {
let chunks = ''
// Handle Response Chunk
res.on('data', chunk => (chunks += chunk))
// Handle Response Ended, print response body
res.on('end', () => console.log(chunks))
})
jsonPostRequest.write(requestBody)
jsonPostRequest.end()

Related

React-Native JSON Parse error: Unexpected identifier "var"

Im trying to make a login screen for my react-native app, but when I try to login I get the error message 'JSON Parse error: unexpected token "var" ' displayed.
I have a react native app and a server app in a different folder which I acces via localhost.
I have tried to change var to let to see what would happen, but then I would get the same error, but with let instead.
This is my react-native code
login = () => {
fetch('http://192.168.0.105:8888/loginbackend/routes/users.js', {
method: 'POST',
header: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
My server file
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users'
});
router.POST('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Before, I got JSON Parse error: unexpected token '<', but now its JSON Parse error: unexpected identifier "var". I cant login and cant get an alert if the credentials are incorrect.
Express wasnt set up correctly and in my app file i had 'header' changed that to 'headers'.
app file
login = () => {
fetch('http://localhost:8080/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
"username": this.state.username,
"password": this.state.password,
})
})
.then((response) => response.json())
.then ((res) => {
if (res.success === true) {
AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Profile');
}
else {
alert(res.message);
}
})
.done();
}
}
express file App.js
const port = 8080;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(port, () => console.log(`Backend now listening on ${port}!`));
module.exports = app;
express users.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'users',
port: 8889
});
router.post('/', function(req, res) {
var username = req.body.username;
var password = req.body.password;
connection.query(
"SELECT * FROM user WHERE username = ? AND password = ?",
[username, password], function (err, row){
if (err) {
console.log(err);
res.send({ 'success': false, 'message': 'Kan niet met de database verbinden'});
}
if (row.length > 0 ){
res.send({ 'success': true, 'user': row[0].username });
} else {
res.send({ 'success': false, 'message': 'Gebruiker niet gevonden'});
}
});
});
module.exports = router;
Hope this helps for people who are stuck on the same thing.

Data shows on server response, but not on browser - MySQL Node.js

When I run http://localhost:1337 I get this as my output Hello, [object Object] but on the server response, the output is Hello, David James. It works on the server response but not on the browser.
app.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mywebsite'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error');
} else {
console.log('Connected');
}
});
app.get('/', function(req, res) {
connection.query("SELECT Name FROM chat", function(error, rows, fields) {
if(!!error) {
console.log('Error in the query');
} else {
console.log('SUCCESS!\n');
console.log(rows);
res.send('Hello, ' + rows);
}
});
});
app.listen(1337);
Send it back with JSON.stringify
res.send('Hello, ' + JSON.stringify(rows))

Create an object with mysql query

I can console.log the object that I want, but how can I retrieve the object outside of connection.query()?
var express = require('express');
var mysql = require("mysql");
var app = express();
var connection = mysql.createPool({
connectionLimit: 50,
host: "localhost",
user: "root",
password: "",
database: "sakila"
});
app.get('/', function(req, res){
connection.query('SELECT * FROM actor', function(err, rows) {
if(err) throw err;
var user = rows[0];
console.log(user);
});
res.send();
});
This is the result in the console:
node-databases> node .\database\db-1.js
RowDataPacket {
actor_id: 1,
first_name: 'PENELOPE',
last_name: 'GUINESS',
last_update: 2006-02-15T10:34:33.000Z }
I want to be able to take that and send it in the response to the browser.
Replace console.log with res.send thus sending response within the callback.

Why doesn't this code return json data?

I'm trying to fetch data from database using Node.js and MySQL.
Here's what I'm trying:
var app=require('express')();
var bodyParser=require("body-parser");
var mysql=require('mysql');
var http=require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end();
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: "",
database: 'books'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/book', function(req, res){
var data={
'error': 1,
'Books': ""
};
connection.query("SELECT * FROM book", function(err, rows, fields){
if(rows.length!=0){
data['error']=0;
data['Books']=rows;
res.json(data);
}else{
data['Books']='No books found';
res.json(data);
}
});
});
When I execute node server.js it shows following output in the cmd:
Server running at http://127.0.0.1:8081/
Connected to MySQL
But when I visit to http://127.0.0.1:8081/book, it doesn't display any output.
NOTE: My XAMPP Apache server and MySQL are started.
The problem is, I believe, that you're using two different and redundant web servers. One is http and the other is app (ie. Express). Only http is actually listening on port 8081.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end();
}).listen(8081);
Since all it ever does is write a text/plain header and exit you'll get a blank page no matter what path you try to access.
The other one, app, never listens on a port. So all that app code sets up a server that can't be accessed.
So remove all the http stuff, you don't need it. Express handles this for you. Then call app.listen(8081).
var app = require('express')();
var bodyParser = require("body-parser");
var mysql = require('mysql');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: "",
database: 'books'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/book', function(req, res){
var data={
'error': 1,
'Books': ""
};
connection.query("SELECT * FROM book", function(err, rows, fields){
if(rows.length!=0){
data['error']=0;
data['Books']=rows;
res.json(data);
}else{
data['Books']='No books found';
res.json(data);
}
});
});
app.listen(8081, function () {
console.log('Server running on port 8081');
});

How to provide a mysql database connection in single file in nodejs

I need to provide the mysql connection for modules. I have a code like this.
var express = require('express'),
app = express(),
server = require('http').createServer(app);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
app.get('/save', function(req,res){
var post = {from:'me', to:'you', msg:'hi'};
var query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
if (err) throw err;
});
});
server.listen(3000);
But how we provide one time mysql connection for all the modules.
You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:
every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
You could create db.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then in your app.js, you would simply require it.
var express = require('express');
var app = express();
var db = require('./db');
app.get('/save',function(req,res){
var post = {from:'me', to:'you', msg:'hi'};
db.query('INSERT INTO messages SET ?', post, function(err, result) {
if (err) throw err;
});
});
server.listen(3000);
This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)
I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.
His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db'). You can't because otherwise everytime you access that controller you will be creating a new connection.
To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.
here is a snippet of my code.
mysq_query.js
// Dependencies
var mysql = require('mysql'),
config = require("../config");
/*
* #sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/
var sqlConnection = function sqlConnection(sql, values, next) {
// It means that the values hasnt been passed
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection(config.db);
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
}
});
connection.query(sql, values, function(err) {
connection.end(); // close the connection
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
}
module.exports = sqlConnection;
Than you can use it anywhere just doing like
var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows) {
console.log(rows);
});
UPDATED:
config.json looks like
{
"db": {
"user" : "USERNAME",
"password" : "PASSWORD",
"database" : "DATABASE_NAME",
"socketPath": "/tmp/mysql.sock"
}
}
Hope this helps.
I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.
As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).
Connection Pool Docs
From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:
const mysql = require('mysql');
var connection;
module.exports = {
dbConnection: function () {
connection = mysql.createConnection({
host: "127.0.0.1",
user: "Your_user",
password: "Your_password",
database: 'Your_bd'
});
connection.connect();
return connection;
}
};
Then, the file where you are going to use the connection could be like useDb.js:
const dbConnection = require('./db');
var connection;
function callDb() {
try {
connection = dbConnectionManager.dbConnection();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
console.log(response);
} else {
console.log(error);
}
});
connection.end();
} catch (err) {
console.log(err);
}
}
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'yourip',
port : 'yourport',
user : 'dbusername',
password : 'dbpwd',
database : 'database schema name',
dateStrings: true,
multipleStatements: true
});
// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling
module.exports = function(qry, qrytype, msg, callback) {
if(qrytype != 'S') {
console.log(qry);
}
pool.getConnection(function(err, connection) {
if(err) {
if(connection)
connection.release();
throw err;
}
// Use the connection
connection.query(qry, function (err, results, fields) {
connection.release();
if(err) {
callback('E#connection.query-Error occurred.#'+ err.sqlMessage);
return;
}
if(qrytype==='S') {
//for Select statement
// setTimeout(function() {
callback(results);
// }, 500);
} else if(qrytype==='N'){
let resarr = results[results.length-1];
let newid= '';
if(resarr.length)
newid = resarr[0]['#eid'];
callback(msg + newid);
} else if(qrytype==='U'){
//let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
callback(msg);
} else if(qrytype==='D'){
//let resarr = results[1].affectedRows;
callback(msg);
}
});
connection.on('error', function (err) {
connection.release();
callback('E#connection.on-Error occurred.#'+ err.sqlMessage);
return;
});
});
}
try this
var express = require('express');
var mysql = require('mysql');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin123",
database: "sitepoint"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
module.exports = app;
you can create a global variable and then access that variable in other files.
here is my code, I have created a separate file for MySQL database connection called db.js
const mysql = require('mysql');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "xxxxx",
database: "test"
});
conn.connect((err) => {
if (err) throw err;
console.log('Connected to the MySql DB');
});
module.exports = conn;
Then in the app.js file
const express = require('express');
const router = express.Router();
// MySql Db connection and set in globally
global.db = require('../config/db');
Now you can use it in any other file
const express = require('express');
const router = express.Router();
router.post('/signin', (req, res) => {
try {
var param = req.body;
var sql = `select * from user`;
// db is global variable
db.query(sql, (err, data) => {
if (err) throw new SyntaxError(err);
res.status(200).json({ 'auth': true, 'data': data });
});
} catch (err) {
res.status(400).json({ 'auth': false, 'data': err.message });
}
});