How to perform Insert statement by decoding Base64 in express - node.js

How to decode the param values received which were received as Base64 encoded form and insert into database ?
This is what i have tried.
According to this i am getting one value recieved from the client as
param value and inserting into server ( I have recieved the request
at POST )
No base64 encoding is done here
I am using this code at present :
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '******',
password: "******",
database: 'posting_information_DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1234);
app.use(express.static(__dirname + '/public/images'));
app.post('/Name/',function(request,response,next){
app.use(express.bodyParser());
var keyName=request.query.Key;
var name_of_restaurants;
async.series( [
function(callback) {
connection.query('INSERT INTO details (name) VALUES (?)', [keyName], function (err, rows, fields)
{
console.log('Connection result error ' + err);
callback();
});
}
// Send the response
] );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
What i am trying to do !
Now what changes should i need to make so that when i need recieve a
image and string as two param values
These values are Base64 encoded
How to decode these Base64 here and then insert the retrieved param
values to database
How to modify my posted Express code !
Thanks !

You can retrieve the image parameter using request.params and then create a Buffer object, specify the base64 encoding and then convert it using the .toString() method.
app.post('/Name/', function(request, response, next){
var image = new Buffer(request.params.image, 'base64').toString('binary');
// do the database insert...
});

Related

Why my restful API stuck when I put integer as parameter in the url using node.js

I'm trying to get data in JSON format. I just copied an old project and changed it IP address to database, username, port, password and database name.
When I try to access data through this addres: localhost:3000/&id=13
The browser just doesn't load them.
When I enter the address with the port without / I see the message with error:
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
The same code is pinned to another database and I see the data in JSON format.
I checked 10 times if the username, password, port and database name are correct and they are fine.
The code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 3000
var pool = mysql.createPool({
connectionLimit: 10,
host: '192.168.0.1',
user: 'user',
port: '3388',
password: 'password',
database: 'databasename'
});
var ardaforecast = '';
app.route('/')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
//const date = req.query.date;
const id = req.query.id;
pool.query(`CALL Get_Alert_levels_Station(${id})`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
aladinModel = result;
res.json({ ardaforecast })
});
});
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
pool.on('error', function (err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
app.use(function (req, res) {
res.status(404);
})
;
Can I get an example of how I can fix this or how to find out where the problem is ?
You can use this one to see how what your url contains: https://www.freeformatter.com/url-parser-query-string-splitter.html
In your example, the problem is that you're using & (ampersand), but what it does is separating multiple query parameters. Since you have just one, your url is not properly structured and does not contain any parameters whatsoever.
You should use ? (question mark) to denote the first one:
localhost:3000/?id=13
p.s. Успех ;)

Mongoose validation CastError: Cast to string failed for value

I am trying to run my .js script in node but while adding some new data in database the server is not loading and giving this error(CastError: Cast to string failed for value). I am not getting the error can someone please help me out?Attaching the SS of cmd and the code as well![enter image description here][1]
Code is as follows:
var express=require("express");
var app= express();
var bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
var mongoose=require("mongoose");
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology",true);
mongoose.connect("mongodb://localhost/yelp_camp");
var campgroundsschema= new mongoose.Schema({
name:String,
image:String
});
var Campground= mongoose.model("Campground",campgroundsschema);
//Campground.create(
// {
// name:"Granite Hill",
//image:"https://images.unsplash.com/photo-1487750404521-0bc4682c48c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"
//},function(err,campgrounds){
//if(err){
// console.log(err);
//}
//else{
// console.log("We have created a new campground");
// console.log(campgrounds);
//}
//}
//)
app.get("/",function(req,res){
res.render("landing");
});
app.get("/campgrounds",function(req,res){
Campground.find({},function(err,allCampgrounds){
if(err){
console.log(err);
}
else{
res.render("campgrounds",{campgrounds:allCampgrounds});
}
});
});
app.post("/campgrounds",function(req,res){
var name=req.body.name;
var image=req.body.image;
var newCampground={name: name,image: image};
Campground.create(newCampground,function(err,newlyCreated){
if(err){
console.log(err);
}
else{
console.log("we have created a new campground here!!");
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new",function(req,res){
res.render("newcamp.ejs");
});
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Example app listening on port ' + port + '!');
});
Error ScreenShot: [1]: https://i.stack.imgur.com/9vNPz.png
( please open this link to view the image)
Looking at the image link that you attached in the body. I can see that you are sending an array of string which apparently looks like this
[ "C1", "A URL" ]
which is actually an array data type, whereas the type that you have set in your schema for name is String.
If you want to save an array of strings? You must change the data type to Array of strings i.e.
name: [String]
or you can stringify the array that you are sending. Using
JSON.stringify(yourArray)
This is the url to data types of mongoose so you can explore other data types as well.
UPDATE
var image = JSON.stringify(req.body.image);
In the above chunk of code i stringified the array of images. And then I tried to save it and its working.

How to output mongodb collections in nodejs app to get them in response

I am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database and adding record to collection.
Now I want to send the collection info in return. But using res.send(collectionInfo); is not working.
Let me know how should I achieve this
Below is the code of my server.js file
var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.get('/monogdb', function (req, res) {
res.render('monogdb.ejs');
});
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
mongoClient.close();
//res.setHeader('Content-Type', 'application/json');
res.send(collectionInfo);
}
})
})
As per #Roman Sachenko answer, I have tried to use
res.send(collectionInfo.toJSON()); but it is giving below error
/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Object #<Collection> has no method 'toJSON'
at /home/ubuntu/workspace/server.js:66:41
at MongoClient.open
(/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
and using res.send({data: collectionInfo}); gives error
home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.res.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:185:19)
at ServerResponse.res.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:117:21)
at /home/ubuntu/workspace/server.js:67:21
at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
Try to return this: res.status(200).json({'myCollection' : collectionInfo});.
You can find more details about express response here
Update:
After you explain the details, take a look at the code below:
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
res.status(500).json({message : 'OMG, an error occurred'});
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
// Here we will find all students
collectionInfo.find({}).toArray(function(err, students) {
// so now, we can return all students to the screen.
res.status(200).json({'myCollection' : students});
}
}
})
})
Cheers!
Mongoose ODM
First of all I would like to recommend you using Mongoose ODM:
https://github.com/Automattic/mongoose
So you will make you work with database much easier.
Basically it returns (Mongoose) normal object as results, but in case of issues you may try to use toObject() or toJSON() or as it mentioned create own object like {data: mongoCollection}
Examples:
res.send(collectionInfo.toObject());
res.send(collectionInfo.toJSON());
res.send({data: collectionInfo});
Please refer to the link in case of questions:
http://mongoosejs.com/docs/guide.html#toJSON
Native Driver
As for native driver, it also should return normally-constructed object, but according to issues I faced with in the past, JSON.stringify always helps if you set headers manually.
You may also check the contents of your entity. So you can just output it by console.log(collectionInfo);
Then just make sure that there is correct object inside.
And according to results you can take actions like:
res.send(JSON.stringify(collectionInfo)) //set headers manually
res.json(JSON.stringify(collectionInfo)) //you don't need to set headers
At least you will know what exactly is inside of collectionInfo. I think it will be enough to investigate the issue.
You can view circular JSON objects by doing this in node.js:
const util = require('util') // Native node module
util.inspect(circularObj)
You can call it from anywhere in the code, so it's very versatile.

How can I respond in XML using ExpressJS?

I have a simple code that gives a JSON response for a specific route. Here's my current code:
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '****',
password: "****",
database: 'restaurants'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1235);
app.use(express.static(__dirname + '/public/images'));
app.get('/DescriptionSortedRating/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants ORDER BY restaurantRATING', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
How can I make an XML response equivalent to the JSON above?
You can use any number of the XML libraries available on npm. Here's an example using the simply-named "xml" library:
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(name_of_restaurants));
See the module's documentation for a description of how it converts JavaScript objects to XML. If you need things returned in a specific XML format, you'll have more work to do, of course.
As an update to this, it looks like res.type should be used instead as res.set does not give the same results.
res.type('application/xml');
More information can be found in the API reference.

Express in server to perform a database query

I want to know how ExpressJS works in the server side
I need some information on Server side, Main things are,As per my knowledge,
ExpressJS can perform all the functionalists of a PHP - - - IS it
true ?
My Client(Android) is ready to submit a POST request to Server
If i can send one single information in the form of (Key,value) pair,
can the Express accept that pair- - Identify the value based on key
and, to perform a sql query to Database based on the value received
from android client?
If it can how it does it?
MY Express Program ( It gives a Response without scenario explained above - How to modify this program )
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*********',
password: "*****",
database: 'DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7002);
//
//REQUEST FOR FIRST REQUEST
//
app.get('/',function(request,response){
var name_of_restaurants, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields)
{
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Hope I am clear
Thanks ,
You can send information via query params or as part of the url path. If you send it as a query param, you can access it using
req.query.keyName;
If you want to send the value as part of the url, you'll have to add a route to accept it. You can accept variable content in a url by using the :keyName form. Express will capture it in req.params. So it would look a little like this:
app.get('/some/url/:keyName', function(req, res, next){
var keyName = req.params.keyName;
// . . .
});
Then you can send your http request to '/some/url/someKeyValue' and the variable keyName will then be equal to whatever you add after /some/url/.
If you're POSTing data in the body of the request, access it with req.body.keyName.
EDIT: Here's an attempt at using the original code. Note that I'm still making up values and guessing at what the intent is.
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*********',
password: "*****",
database: 'DB'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7002);
//
//REQUEST FOR FIRST REQUEST
//
app.get('/',function(request,response){
var name_of_restaurants, RestaurantTimings;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM restaurants WHERE name = ' . request.body.name, function(err, rows, fields) {
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
},
// Get the second table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantTimings', function(err, rows, fields) {
console.log('Connection result error '+err);
RestaurantTimings = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants,
'RestaurantTimings' : RestaurantTimings
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
But you should really not query directly like that because of SQL injection. I've never used MySQL from node, but I'm sure there is some way to use parameterized queries. Hope this is more helpful.
Also, I'm assuming that the data will be passed in the request body, since you said you are ready to POST to the server.

Resources