I would like to fetch all the data (users) from a localdb using mongodb and node.js. but res.json(usersArray) is not displaying anything. I also tried to use .render but it would give me another error.
var express = require('express');
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost/mydb', ['users']);
var app = express();
const port = 5000;
app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res){
console.log("I received a GET request")
/*
db.users.find(function(err, docs){
console.log("Getting data from db");
console.log(docs);
//res.json(docs);
});
*/
let usersArray = db.users.find().toArray(function(err, docs){
console.log("Getting data from db");
console.log(docs);
//res.json(docs);
});;
res.json(usersArray);
//usersString = JSON.stringify(usersArray);
//res.render(usersString);
//res.json(usersString);
console.log("Returned data");
});
app.listen(port,'0.0.0.0');
console.log('Server running on port '+port);
use async await to block promise-based asynchronous functions
app.get('/', async function(req, res){
console.log("I received a GET request")
let usersArray = await new Promise((resolve, reject) => {
db.users.find().toArray((err, docs) => {
if (err)
reject(err)
resolve(docs)
})
});
res.json(usersArray);
//usersString = JSON.stringify(usersArray);
//res.render(usersString);
//res.json(usersString);
console.log("Returned data");
});
Related
I am new to programming I tried to Use ElephantSql postgres database server in node..but its not connecting..(i used the same code from doumentation.)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(cors())
app.use(bodyParser.json());
var pg = require('pg');
var client = new pg.Client("postgres:/.elephantsql.com:The Actual url");
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
// >> output: 2018-08-23T14:02:57.117Z
client.end();
});
});
app.get('/', (req, res) => { res.send('its working') })
app.listen(PORT, () => {
console.log(`app is running on PORT:${PORT}`);
})
Removing client.end() worked for me. You can then use client.query in your routes to run queries.
For example,
app.get('/', async (req, res) => {
try {
const results = await client.query('SELECT * FROM your_table');
res.json(results);
} catch (err) {
console.log(err);
}
}
I would however suggest putting the block of code that you copied in a separate file as the documentation says. Then export client.
For example, we'll call the file elephantsql.js
var pg = require('pg');
var client = new pg.Client("postgres:/.elephantsql.com:The Actual url");
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
// >> output: 2018-08-23T14:02:57.117Z
});
});
module.exports = client;
Then, all you need to do is require the client variable wherever your routes are and you can use client.query again.
const client = require('./elephantsql');
app.get('/', async (req, res) => {
try {
const results = await client.query('SELECT * FROM your_table');
res.json(results);
} catch (err) {
console.log(err);
}
}
So I'm trying to create a node app that calls an ldap serve and to authenticate users. In the code below, the app successfully connects to the server and processes the request. But when I try to send a response back, I get this error:
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I'm not really sure why this is occurring. I'm pretty new to node, express, and ldap
// ldapjs required for ldap connection
const ldap = require('ldapjs');
//express required for exposing endpoints
const express = require('express');
const app = express();
const assert = require('assert');
var client = ldap.createClient({
url: 'ldap://someserve.com'
});
//Search filter for users in the directory
var opts = {
filter: '(&(objectCategory=person)(objectClass=user))',
scope: 'sub',
};
//General Ldap serch user
var UserName = '123.test.com';
var Pass = '123longpass'
//Base URL
app.get('/', (req,res) => {
res.send('hello from node')
});
//Get all ldap users
app.get('/api/ldapUsers', (req, res) =>
{
client.bind(UserName, Pass, function (err)
{
client.search('DC=sdf,DC=sdfa,DC=gdfgd', opts, function (err, search)
{
search.on('searchEntry', function (entry)
{
res.setHeader('Content-Type', 'application/json');
var users = entry.object;
console.log(users);
res.json(users);
res.end();
});
});
});
// client.unbind( err => {
// assert.ifError(err);
// });
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
searchEntry event is called once for each found item which means you are calling res.json multiple times.
Try this:
app.get('/api/ldapUsers', (req, res) =>
{
client.bind(UserName, Pass, function (err)
{
client.search('DC=sdf,DC=sdfa,DC=gdfgd', opts, function (err, search)
{
var users = [];
search.on('searchEntry', function (entry) {
users.push(entry.object);
});
search.on('end', function (entry) {
res.setHeader('Content-Type', 'application/json');
console.log(users);
res.json(users);
res.end();
});
});
});
});
I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.
I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
I need an API to insert data from android to mongodb , I follow this ,the code can run , have NO error , and I use POSTMAN try to post some data , it always say could not get any respone , seem to have an error connecting to 192.168.1.105:3000/songs
but I can use find all api and findByID.
This took me hours , please help , so depress :(
app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
songs = require('./routes/route');
var jsonParser = bodyParser.json();
app.post('/songs', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.get('/songs',songs.addSong);
route
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://XXXX:XXXX#ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.findAll = function(req, res) {
db.collection('songs',function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving song: ' + id);
db.collection('songs', function(err, collection)
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.addSong = function(req, res) {
var song = req.query;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
{console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
};
Okay so I changed a few things in your code. I'm successfully getting the request body in the app.js file. Do have a look at the code.
route.js
var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://localhost:27017/test";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
console.log("mongodb is connected!!");
});
exports.addSong = function(req, res) {
var song = req.body;
console.log('Adding song: ' + JSON.stringify(song));
db.collection('songs', function(err, collection) {
collection.insert(song, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
});
});
}
Notice that I have changed the URI to localhost, so change it again to the one you specified.
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
songs = require('./routes/route');
app.post('/songs', function(req, res) {
console.log("Request.Body : " + JSON.stringify(req.body));
if (!req.body) return res.sendStatus(400);
songs.addSong(req, res);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/songs',songs.addSong);
Since your only problem was that you weren't able to get the request body. You'll be able to get it with this code.
Also since your app.get('/songs',songs.addSong); is of type GET, you'll not be able to send POST Data through it. So change it to
app.post('/songs',songs.addSong);
Hope this helps.