POST request is empty using ExpressJS - javascript

When I do a POST request to my server's route, the request.body is empty. And I'm using body parser to obtain JSON data. What I'm doing wrong?
On the _saveTicket function, I have console.log to show all the body request parameters. And when I do a POST request, request.body is empty.
What I need to parse it automatically ?
server.js
/**
* Declaration
**/
var express = require('express'),
database = require('./config/database.js'),
morgan = require('morgan'),
port = 2559,
bodyPar = require('body-parser'),
methodOv = require('method-override'),
mongoose = require('mongoose'),
fsr = require('file-stream-rotator'),
logDirectory = __dirname + '/log',
favicon = require ('serve-favicon');
app = express();
/**
* DB Connection
**/
mongoose.connect(database.mongo);
/**
* Api definition
**/
var accessLogStream = fsr.getStream({
date_format: 'YYYYMMDD',
filename: logDirectory + '/access-%DATE%.log',
frequency: 'daily',
verbose: false
})
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined', {stream: accessLogStream}));
app.use(bodyPar.urlencoded({'extended':'true'}));
app.use(bodyPar.json());
app.use(bodyPar.json({ type: 'application/vnd.api+json' }));
app.use(methodOv('X-HTTP-Method-Override'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));
/**
* Routes section
**/
require('./routes/ticket.js')(app);
/**
* Starting server
**/
app.listen (port)
console.log ("Listening on port: " + port);
model/ticket.js
var mongoose = require('mongoose');
var TicketSchema = new mongoose.Schema({
title: String,
description: String
}, {versionKey: false});
module.exports = mongoose.model('Ticket', TicketSchema, 'Ticket');
routes/ticket.js
var Ticket = require('../models/ticket');
module.exports = function(app){
_getAllTickets = function(req, res){
var query = Ticket.find().lean();
query.exec(function(err, lst){
if(err)
res.send(err);
res.json(lst);
});
};
_saveTicket = function(req, res){
console.log(req.body);
var tckt = new Ticket({
title: req.body.title,
description: req.body.description
});
tckt.save(function(err){
if(!err)
console.log('Ticket creation successful. ');
else
console.log('ERROR: ' + err);
});
res.send(tckt);
};
app.get('/api/tickets/', _getAllTickets);
app.post('/api/tickets/', _saveTicket);
}

Make sure that the HTTP request has the Content-Type header set to be application/json or x-www-form-urlencoded based on your body-parser middleware definitions. My guess is that its coming through right now as neither of those Content-Type's

Related

How to retrieve path of image from mongoDB using Nodejs

I have uploaded the image in to a local directory using Busboy and passed
the path of the image to the MongoDB using Mongoose but now I unable to
retrieve the path
to display the image in my ejs view. I'm new to this nodejs. Please help me
to display the image.
Thank you Very much in Advance :)
var express = require('express'); //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.set('view engine','ejs');
app.use(express.static(__dirname + '/public'));
var nameSchema = mongoose.Schema({
newfile: Object,
path: String
});
var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
res.render('index',{'title': 'New post app'});
});
app.route('/')
.post(function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
var dirname = path.join(__dirname + '/public/uploads/' + filename);
file.pipe(fstream);
//mongo save
var paths = new compileSchema({newfile : dirname, passReqToCallback: true});
paths.save(function(err){
if(err) throw err;
compileSchema.find({newfile: dirname}, (err, result) =>{
console.log();
return result;
});
});
fstream.on('close', function () {
console.log("Upload Finished of " + filename);
//where to go next
res.redirect('/profile');
});
});
});
app.get('/profile', (req, res)=>{
res.render('profile',{photo: req.result});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
My Ejs file is :
<img src='<%= photo.newfile %>' >
This is the typical process of writing and reading from Mongodb using Mongoose. I have not checked whether your streaming and other things work fine but the db workflow would be better this way.
var express = require('express'); //Express Web Server
var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path'); //used for file path
var fs = require('fs-extra'); //File System - for file manipulation
var mongoose = require('mongoose');
var mongoClient = require('mongodb').mongoClient;
var objectId = require('mongodb').ObjectId;
var app = express();
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/postname');
/* ==========================================================
Create a Route (/upload) to handle the Form submission
(handle POST requests to /upload)
Express v4 Route definition
============================================================ */
app.set('view engine','ejs');
app.use(express.static(__dirname + '/public'));
//You can import your schema like this
const Name = require('./name');
var compileSchema = mongoose.model('foods', nameSchema);
app.get('/', function(req, res, next) {
res.render('index',{'title': 'New post app'});
});
//I have changed your route since it seems to be clashing with the above
app.post('/save' ,function (req, res, next) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
//Path where image will be uploaded
fstream = fs.createWriteStream(__dirname + '/public/uploads/' + filename);
file.pipe(fstream);
var dirname = path.join(__dirname + '/public/uploads/' + filename);
//mongo save
fstream.on('close', function () {
//You can either save to mongodb after streaming closes or while it is streaming but in this case I will do it after.
console.log("Upload Finished of " + filename);
//where to go next
//Declare your schema object here
let name = new Name({
newfile:'Whatever you want to store here',
path: path
});
//Save your declared schema like this
name.save((err) => {
if(err) throw err;
console.log(`saved : ${name}`);
//When you redirect here, it will go to /profile route
res.redirect('/profile');
});
});
});
});
app.get('/profile', (req, res)=>{
//You must retrieve from mongodb your object here if this is where you want the object to be
//{} empty query will find all objects in the table
Name.find({}, (err, result) => {
if(err) throw err;
//after everything was found, send it to front end
res.render('profile',{
photo: req.result,
//Now your 'compileSchema' object is available at front end as 'result' object
result:result
});
});
});
var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});
name.js (create one schema js file for each table you will be working with)
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let compileSchema = new Schema({
newfile: Object,
path: String
});
let Compile = mongoose.model('Compiles', compileSchema);
module.exports = Compile;
Check first that you are receiving and streaming file correctly. If you are, it must work fine. Also, I don't know why you want to save a newfile:object field but all you really need to do is save the path to the image file then retrieve it where you need to use the image and use the path as the <img src='path'> Refer to the comments.

NodeJS res.body is undefined only on one router

I am sending data using swift to a nodeJS server.
Here is the Swift Code:
var data:[String:String] = [:]
data["ABC"] = "nothing"
let req = HTTPRequest(url_to_request: "https://xxx.xxx.xx.x/update", method: HTTPRequest.HTTPRequestMethod.post, data: Profile.toJSON(dict: data))
Here is the NodeJS:
console.log("Server is up!");
var bodyParser = require('body-parser');
var express = require('express');
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bcrypt = require('bcryptjs');
var sslOptions = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8'),
passphrase: 'phrase',
rejectUnauthorized: false
};
var app = express();
//Variables:
var httpPort = 8888;
var httpsPort = 8443;
app.use(bodyParser.urlencoded({
extended: false,
limit: '20mb'
}));
app.use(bodyParser.json({
limit: '50mb'
}));
// parse application/json json size limit
// parse application/x-www-form-urlencoded
// setup server
app.set("port_https", httpsPort);
//check secure connection
app.all("*", function(req, res, next) {
console.log("Secure connection: " + req.secure);
if (req.secure) {
return next();
}
res.redirect("https://" + req.hostname + ":" + app.get("port_https") + req.url);
});
// add User
app.post('/register', register);
//signIn
app.post('/login', logIn);
//Update user's profile details.
app.post('/update', updateProfile);
// Request profile details.
app.post('/profile', profileRequest);
function updateProfile(req, res) {
console.log(res.body); // ---> undefined
}
When I send a post request with data to login, profile, register routers res.body is working well. But when I send data to update for some reason req.body is undefined:
ERROR:
Server: Secure connection: true
Server: undefined #----> log of res.body
Server: Connected successfully to databse!
stderr: /home/asaf/NodeJS/IBQA/IBQA_Server/node_modules/mongodb/lib/mongo_client.js:350
throw err
^
TypeError: Cannot read property 'ABC' of undefined
at /*****/server.js:92:33
at connectCallback (*****/mongo_client.js:428:5)
at /*****/node_modules/mongodb/lib/mongo_client.js:347:11
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
closing code: 1
Your request if there in the req variable, res is used to send the response. Try console.log(req.body)

How to query using MySQL in an EJS File

I am trying to run a query in a view (.ejs file). However, since the keyword require is not defined in a .ejs file, I need to export it from my main file, server.js.
The whole code for my server.js file is below and this is the specific snippet with which I need help.
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
I need to be able to use the mysql.createConnection in my profile.ejs file.
Any help would be great.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
var Connection = require('tedious').Connection;
var config = {
userName: 'DESKTOP-S6CM9A9\\Yash',
password: '',
server: 'DESKTOP-S6CM9A9\\SQLEXPRESS',
};
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "yashm"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql="Select * from test.productlist";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
app.engine('html', require('ejs').renderFile);
exports.profile = function(req, res) {
res.render('profile', { mysql: mysql });
}
//--------------------------------------------------------------------------------
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'test run' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Like already said in the comment, you have to do your query logic in your server.js and then pass the data to your view (or maybe even pre-process it!)
exports.profile = function(req, res) {
con.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
res.render('profile', { data: results });
});
}
In your ejs you can loop trough the data, and acces the fields as data[i]['fieldname']
<ul>
<% for(var i=0; i<data.length; i++) {%>
<li><%= data[i]['id'] %></li>
<% } %>
</ul>

Node.js : get cloudant variable form app.js file

I have the node js application on bluemix. I want to use the cloudant variable on app js from provider js.But it does not work. Please help me review it
app.js
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
fs = require('fs'),
ibmbluemix = require('ibmbluemix'),
ibmpush = require('ibmpush');
var app = express();
var db;
var cloudant;
var fileToUpload;
var dbCredentials = {
dbName : 'my_sample_db',
dbProvider : 'provider'
};
var config = {
// change to real application route assigned for your application
applicationRoute : "http://demo.mybluemix.net"
//for test by postman.
};
// init core sdk
ibmbluemix.initialize(config);
var ibmconfig = ibmbluemix.getConfig();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,IBM-APPLICATION-SECRET,IBM-APPLICATION-ID,IBM-DEVICE-MODEL,IBM-DEVICE-TYPE,IBM-DEVICE-ID,IBM-DEVICE-PLATFORM-VERSION, IBM-DEVICE-NAME,IBM-REQUEST-CORRELATION-ID,X-REWRITE-DOMAIN');
next();
};
app.use(allowCrossDomain);
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
}
function initDBConnection() {
if(process.env.VCAP_SERVICES) {
var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
// Pattern match to find the first instance of a Cloudant service in
// VCAP_SERVICES. If you know your service key, you can access the
// service credentials directly by using the vcapServices object.
for(var vcapService in vcapServices){
if(vcapService.match(/cloudant/i)){
dbCredentials.host = vcapServices[vcapService][0].credentials.host;
dbCredentials.port = vcapServices[vcapService][0].credentials.port;
dbCredentials.user = vcapServices[vcapService][0].credentials.username;
dbCredentials.password = vcapServices[vcapService][0].credentials.password;
dbCredentials.url = vcapServices[vcapService][0].credentials.url;
cloudant = require('cloudant')(dbCredentials.url);
// check if DB exists if not create
cloudant.db.create(dbCredentials.dbName, function (err, res) {
if (err) { console.log('could not create db ', err); }
});
db = cloudant.use(dbCredentials.dbName);
break;
}
}
if(db==null){
console.warn('Could not find Cloudant credentials in VCAP_SERVICES environment variable - data will be unavailable to the UI');
}
} else{
console.warn('VCAP_SERVICES environment variable not set - data will be unavailable to the UI');
}
}
initDBConnection();
app.get('/', routes.index);
function createResponseData(id, name, phone, attachments) {
var responseData = {
id : id,
name : name,
phone : phone,
attachements : []
};
attachments.forEach (function(item, index) {
var attachmentData = {
content_type : item.type,
key : item.key,
url : '/api/favorites/attach?id=' + id + '&key=' + item.key
};
responseData.attachements.push(attachmentData);
});
return responseData;
}
function createResponseDataProvider(id, provider_type, name, phone, mobile, email, logo, address) {
var responseData = {
id : id,
provider_type: provider_type,
name : name,
phone : phone,
mobile: mobile,
email: email,
logo: logo,
address : address
};
return responseData;
}
//=============get api/rovider/:id================
app.use("/", require('./lib/provider'));
require('./lib/provider');
module.exports.cloudant=cloudant;
module.exports.cloudant1="demo";
http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
console.log('Express server listening on port ' + app.get('port'));
});
and provider.js file
var router = require('express').Router();
var cloudant= require('../app').cloudant;
var cloudant1= require('../app').cloudant1;
//create del all whitespace of string function
String.prototype.delAllWhiteSpace = function() {
return this.split(' ').join('');
};
var Providers = {
getProvider: function(req, res){
console.log(cloudant);
console.log(cloudant1);
}
};
router.get('/abc/provider/', Providers.getProvider);
module.exports = exports = router;
when calling API http://demo.mybluemix.net/abc/provider, the return results are cloudant undefined

ExpressJS POST Method Request Issue

I am running into an issue where I am trying to run a POST request via Postman and I get a loading request for a long time and then a Could not get any response message. There are no errors that are appearing in terminal. Is it the way I am saving the POST? Specifically looking at my /blog route.
server.js
//Load express
var express = require('express');
var app = express();
var router = express.Router(); // get an instance of the router
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
// configure app to use bodyParser()
// get data from a POST method
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set the port
var blogDB = require('./config/blogDB.js');
var Blogpost = require('./app/models/blogModel');
app.set('view engine', 'ejs'); // set ejs as the view engine
app.use(express.static(__dirname + '/public')); // set the public directory
var routes = require('./app/routes');
// use routes.js
app.use(routes);
app.listen(port);
console.log('magic is happening on port' + port);
blogModel.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title : String,
body : String,
date_created : Date
});
module.exports = mongoose.model('Blogpost', BlogPostSchema);
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
//index
router.route('/')
.get(function(req, res) {
var drinks = [
{ name: 'Bloody Mary', drunkness: 3 },
{ name: 'Martini', drunkness: 5 },
{ name: 'Scotch', drunkness: 10}
];
var tagline = "Lets do this.";
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
//blog
router.route('/blog')
.get(function(req, res) {
res.send('This is the blog page');
})
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.name; // set the blog title
blogpost.body = req.body.body; // set the blog content
blogpost.date_created = Date.now();
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
The issue was that I did not setup a user for my Mongo database. Basically it couldn't gain access to the user/pw to the database that I was using. Once I created a user matching the user/pw I included in my url, then I was able to get a successful post.

Categories

Resources