I am making an app where the app is going to send the POST request data to the nodeJS server. The JSON format of the content looks like: {"encrypteddata": "someencryptedvalueofthetext"}. This data will be saved in a MongoDB.
I created two file one is app.js and another is /models/encdata.js. Content of both the file is given below.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
ENCDATA = require('./models/encdata');
mongoose.connect('mongodb://localhost/encdata', { useMongoClient: true }); // the url access the database
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Visit /api/encdata');
app.get('/api/encdata', function(req, res){
ENCDATA.getENCDATA(function(err, encdata){
if(err){
throw err;
}
res.json(encdata);
});
});
app.post('/api/encdata', function(req, res){
var encdata = req.body;
ENCDATA.addENCDATA(encdata, function(err, encdata){
if(err){
throw err;
}
res.json(encdata);
});
});
});
app.listen(3000);
console.log('Running on port 3000');
encdata.js
var mongoose = require('mongoose');
var encdataencryptSchema = mongoose.Schema({
encrypteddata: {
type: String,
required: true
}
});
var ENCDATA = module.exports = mongoose.model('encdata', encdataencryptSchema);
module.exports.getENCDATA = function(callback, limit){
ENCDATA.find(callback).limit(limit);
}
module.exports.addENCDATA = function(encdata, callback){
ENCDATA.create(encdata, callback);
}
And data in MongoDB is:
{"encrypteddata": "someencryptedvalueofthetext"}
But when I make a GET request to the url localhost:3000/api/encdata it shows [] (an empty array although I have data). Even the POST request is not working and I am not able to save any data.
I rewrote your code by changing the name of the variable and it worked for me. The app.js file looks something like this:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var http = require('http');
app.use(bodyParser.json());
AES = require('./models/aes');
mongoose.connect('mongodb://localhost/aes', { useMongoClient: true }); // the url access the database
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Visit /api/aes');
app.get('/api/aes', function(req, res){
AES.getAES(function(err, aes){
if(err){
throw err;
}
res.json(aes);
});
});
app.post('/api/aes', function(req, res){
var aes = req.body;
AES.addAES(aes, function(err, aes){
if(err){
throw err;
}
res.json(aes);
});
});
});
app.listen(3000);
console.log('Running on port 3000');
In the encdata.js you can change the variable to AES. Name the mongodb collection and database as aes.
Related
I am trying to do my first API Rest and I am following some tutorials. I am requesting all the articles in a MongoDB database.
This is the code of the main:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require('mongoose');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
// Import Models and controllers
var models = require('./models/article')(app, mongoose);
var articleCtrl = require('./controllers/articleController');
// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
articles.route('/articles/:id')
.get(articleCtrl.findById);
articles.route('/articles')
.get(articleCtrl.findAllarticles)
.post(articleCtrl.addarticle);
app.use('/api', articles);
app.use(router);
mongoose.connect('mongodb://localhost/ustcg', { useNewUrlParser: true ,useUnifiedTopology: true}, function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
The code of the controller is here:
// Import article and mongoose
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
//GET - Return a article with specified ID
exports.findById = function(req, res) {
Article.findById(req.params.id, function(err, Article) {
if(err) return res.send(500, err.message);
console.log('GET /article/' + req.params.id);
res.status(200).jsonp(Article);
});
};
//GET - Return all articles in the DB
exports.findAllarticles = function(req, res) {
Article.find(function(err, Article) {
if(err) res.send(500, err.message);
console.log('GET /article')
res.status(200).jsonp(Article);
});
};
//POST - Insert a new article in the DB
exports.addarticle = function(req, res) {
console.log('POST');
console.log(req.body);
var Article = new Article({
title: req.body.title,
paragraphs: req.body.paragraphs
});
Article.save(function(err, Article) {
if(err) return res.send(500, err.message);
res.status(200).jsonp(Article);
});
};
The model:
//We create the model
exports = module.exports = function(app, mongoose) {
var ArticleSchema = new mongoose.Schema({
title: { type: String },
paragraphs: { type: Array },
});
mongoose.model('Article', ArticleSchema);
};
When I tried to request the following http request it send me 404 error. I can not see any logs on the console so it is not entering the methods in order to see the exception is happening so I am stucked with this...
If someone could help me it would be nice.
what is articles variable in your main file.
I tried your code in my machine and struggled with articles variable and you have extra imports which are not required.
Try following code it works fine
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var articleCtrl = require('./sample.controller');
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
router.get('/articles/:id', articleCtrl.findById);
router.post('/articles', articleCtrl.addarticle);
router.get('/articles', articleCtrl.findAllarticles)
// app.use('/api', router);
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
if you uncomment app.use('/api', router); then you can also use routes as localhost:3000/api/articles
I'm trying to build a RESTful webservice following this tutorial:
https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
It's not working returning me a CANNOT GET/ reports error...
I'm trying to learn node.js and I can't find the error anywhere and everything I tried didn't work.
Also, when I call the server, it reaches to index.js which prints a "HEY". Wasn't this supposed to reach server.js first?
Here is my code:
Server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Report = require('./api/models/reportModel.js'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/server');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/reportRoute.js');
routes(app);
app.listen(port);
console.log('Report RESTful API server started on: ' + port);
reportRoute.js
'use strict';
module.exports = function(app) {
var reports = require('../controllers/reportController.js');
// report Routes
app.route('/reports')
.get(reports.list_all_reports)
.post(reports.create_a_report);
app.route('/reports/:reportId').get(reports.read_a_report)
.put(reports.update_a_report)
.delete(reports.delete_a_report);
};
reportController.js
'use strict';
var mongoose = require('mongoose'),
Report = mongoose.model('Reports');
exports.list_all_reports = function(req, res) {
Report.find({}, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.create_a_report = function(req, res) {
var new_report = new Report(req.body);
new_report.save(function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.read_a_report = function(req, res) {
Report.findById(req.params.reportId, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.update_a_report = function(req, report) {
Report.findOneAndUpdate({_id: req.params.taskId}, req.body, { new: true }, function(err, report) {
if (err)
res.send(err);
res.json(report);
});
};
exports.delete_a_report = function(req, res) {
Report.remove({
_id: req.params.reportId
}, function(err, report) {
if (err)
res.send(err);
res.json({ message: 'Report successfully deleted' });
});
};
Thank you for your help...
EDIT:
index.js
const express = require('express');
const app = express();
var route = require('./api/routes/reportRoute');
app.get('/', function(req, res) {
res.send('HEY!');
})
app.listen(3000, function(){console.log('Server running on port 3000')});
You haven't posted your reportController.js but this problem will occur if the function list_all_reports does not set a response body. For example, adding
res.json({hello: "world"});
to the handler function should make it work.
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>
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.
I struggle while trying to do a simple mongoDB query from within my express app:
app.js
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongourl = ''; // omitted on SO
var MongoClient = require('mongodb').MongoClient;
var dbInstance;
MongoClient.connect(mongourl, function(err, db) {
db.on('open',function(){
dbInstance = db;
})
});
app.get('/', routes.index(dbInstance));
http.createServer(app).listen(app.get('port'), function(){
});
routes/index.js
exports.index = function(db){
return function(req,res){
}
};
Do i understand correctly that the exports.index' paramter is a database instance? If so, why can't i do db.getCollectionNames()?
How would i work with the database instance in my route?
node.js is asynchronous. This means that db and so dbInstance do not exist after the Mongoclient.connect() function call, but within the callback. So your code has to look like:
MongoClient.connect(mongourl, function(err, db) {
...
app.get( '/', routes.index( db ) );
...
});