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
Related
Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})
I tried every possible solutions that I found, but none of them working. The body-parser is installed, the front-end is also correct. When I send a form, the url is
/addChess?name=123&hp=123&damage=123&skill=1&class=1
However, the req.body is undefined. My code:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// DataBase
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "chess"
});
con.connect(function(err) {
if (err) {
console.log('connecting error');
return;
}
console.log('connecting success');
});
// view engine setup
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');
// 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')));
// db state
app.use(function(req, res, next) {
req.con = con;
next();
});
app.get('/', function(req, res, next) {
var db = req.con;
db.query('SELECT chess.name AS name, chess.health AS health, chess.damage AS damage, skill.name AS skill, class.name AS class FROM chess, skill, class WHERE chess.class = class.classID AND chess.skillID = skill.skillID', function(err1, rows1) {
if (err1) {
console.log(err1);
}
db.query('SELECT name,skillID FROM skill',function(err2, rows2){
if (err2) {
console.log(err2);
}
db.query('SELECT name,classID FROM class',function(err3, rows3){
if (err3) {
console.log(err3);
}
res.render('index', {data: rows1, skillList: rows2, classList:rows3});
});
});
});
});
app.get('/addChess', function(req, res, next) {
var db = req.con;
var sql = {
name: req.body.name,
health: req.body.hp,
damage: req.body.damage,
skillID: req.body.skill,
class: req.body.class
};
//console.log(sql);
var qur = db.query('INSERT INTO chess SET ?', sql, function(err, rows) {
if (err) {
console.log(err);
}
res.setHeader('Content-Type', 'application/json');
console.log(qur.sql);
console.log(req.headers);
res.redirect('/');
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
module.exports = app;
These are not body params but ordinary request parameters. Use req.query.name etc instead. Check the documentation here: http://expressjs.com/en/api.html#req.query
Body parameters is what you usually pass when doing an HTTP POST request.
When you submit a form using the GET HTTP method, the form fields are sent in the querystring, which is not parsed by the body-parser module. For parsing the querystring, you can use url.parse(req.url, true).querystring.
I have a really simple backend with a couple routes. I want to keep the route logic outside the server.js file but for some reason when I do a POST request to the route it gives me a 404.
server.js
// Call packages
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
var config = require('./config.js');
var mongoose = require('mongoose');
var path = require('path');
var mandrill = require('mandrill-api/mandrill');
var mandrill_client = new mandrill.Mandrill(config.mandrillApi);
var favicon = require('serve-favicon');
// Set up morgan to log HTTP requests
app.use(morgan('dev'));
// Set up mongo database
mongoose.connect(config.database);
// Parse body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Server favicon
app.use(favicon(path.resolve('../client/content/images/logos/website-brand.png')));
//Routes
app.use('/sendMail', require(__dirname + '/routes/sendMail.js'));
// Default Routes
app.get('/', function (req, res) {
res.sendfile(path.resolve('../client/views/index.html'));
});
app.get('/:name', function (req, res) {
res.sendfile(path.resolve('../client/views/index.html'));
});
//Serve static files
app.use(express.static(path.resolve('../client')));
app.use('/scripts', express.static(path.resolve('../node_modules/angular-ui-bootstrap')));
app.use('/scripts', express.static(path.resolve('../node_modules/requirejs')));
//Log requests
app.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});
//Start server
app.listen(config.port, function() {
console.log('I\'m listening on port ' + config.port);
});
And sendMail.js
var config = require('../config.js');
var express = require('express');
var router = express.Router();
var mandrill = require('mandrill-api/mandrill');
var mandrill_client = new mandrill.Mandrill(config.mandrillApi);
// Routes
router.post(sendMail);
module.exports = router;
function sendMail(req, res, next) {
console.log("Receiving in sendMail");
var name = req.body.name;
var email = req.body.email;
var message = req.body.message;
var toSend = {
"html": "<p>"+message+"</p>",
"text": message,
"subject": "From Website",
"from_email": email,
"from_name": name,
"to": [{
"email": "",
"name": "",
"type": "to"
}]
};
mandrill_client.messages.send({"message": toSend}, function(result) {
console.log(result);
var status = result[0].status;
if (status == 'sent') {
res.send({success: true});
} else {
res.send({success: false, reason: status});
};
}, function(e) {
console.log("Mandrill Error: "+e.message);
res.send({success: false, error: e});
});
next();
};
But when I do a POST request to /sendMail it gives me a 404
enter image description here
In sendMail.js remove at the end of file :
next();
because in this route your responses are in async callback, and before they are invoke, node.js get next() and therefore it move to next router. Because there is no more accurate routes it return 404.
One offtopic in server.js:
Move your log request before sendMail router.
I am pretty new with node.js and express so bear with me please.
I am wondering how i can get a mysql instance and use it in my controller. I have 4 files that look like this:
see my comment in the controller.js file
server.js :
var express = require('./config/express');
var app = express();
module.exports = app;
app.listen(3000);
console.log('server running');
express.js :
var express = require('express'),
bodyParser = require('body-parser'),
mysql = require('mysql');
module.exports = function() {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('views','./app/views');
app.set('view engine','ejs');
//NOT SURE WHAT TO DO HERE OR WHERE TO PUT THE CONNECTION DETAILS
var dbConnection = mysql.createConnection({
host : 'localhost',
user : 'someuser',
database : 'somedb',
password : 'somepass'
});
//connection.connect();
//
//connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
//});
//
//connection.end();
require('../app/routes/index.server.routes.js')(app);
app.use(express.static('./public'));
return app;
};
routes.js :
module.exports = function(app) {
var index = require('../controllers/index.server.controller');
app.get('/', index.render);
app.post('/', index.stuff);
};
controller.js :
exports.render = function(req, res) {
//DO DB STUFF HERE
res.render('index', {
title: 'this is the title'
});
};
exports.stuff = function(req, res) {
res.render('index', {
title: 'this is the title post'
});
};
To use the connection instance in your controller, you'll need to pass it from the express.js file to the controller.js file. The first step is to pass the connection instance to the router:
express.js
require('../app/routes/index.server.routes.js')(app, connection);
This will make it available in the routes.js file. You then need to pass the same connection instance to the controller.
index.server.routes.js
module.exports = function(app, connection) {
var index = require('../controllers/index.server.controller')(connection);
app.get('/', index.render);
app.post('/', index.stuff);
};
The controller will need to be refactored so it takes a connection instance as an argument:
index.server.controller.js
function IndexController(connection) {
controllerMethods = {};
controllerMethods.render = function (req, res) {
// You can use the connection instance here.
connection.connect()
// Run your query
connection.end()
...
};
// Define other methods for the controller
// Return the object that holds the methods.
return controllerMethods;
}
module.exports = IndexController;
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.