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);
}
}
Related
I'm a beginner and try to create a rest API following this tutorial. I expected to see Server is running on port: ${PORT}, but it seems like my code can't reach it. I got no error on my terminal and it looks like this
Here are my code:
server.js
require('dotenv').config({ path: './config.env' });
const express = require('express');
const cors = require('cors');
const dbo = require('./db/conn');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
app.use(require('./api/api'));
// Global error handling
app.use(function (err, _req, res) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
});
conn.js
const MongoClient = require('mongodb').MongoClient
const dotenv = require("dotenv")
dotenv.config()
const connectionString = process.env.MONGOURI
let db;
module.exports = {
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
db = client.db('db-name');
console.log('Connected to Database');
return callback
});
},
getDb: function () {
return db;
}
}
api.js
const express = require("express");
const gameRoutes = express.Router();
const dbo = require('../db/conn');
gameRoutes.route("/game").get(async function (_req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("game")
.find({}).limit(50)
.toArray(function(err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
})
})
module.exports = gameRoutes;
Can you please tell me what's wrong with my code? I really can't find why the server is not running. Thanks in advance! I'll be very grateful for your help!
In your connectToServer method you just returning the callback. But you actually need to call it as well.
So change this
return callback
to this
return callback(null);
If you want to pass the possible error from MongoClient to the callback as well, then change your connectToServer method to this :
connectToServer : function(callback) {
MongoClient.connect(connectionString, {
useUnifiedTopology: true
}, (err, client) => {
if (err) { return callback(err); }
db = client.db('db-name');
console.log('Connected to Database');
return callback(null) // no error, so pass "null"
});
}
I'm trying to get data from a collections database in my MongoDB using Node, which I've done successfully. My only problem is how to render the obtained data from the collections and posting it into the express app.
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close()
})
})
}
main().catch(console.error)
I solved my own problem by just performing an app.get() in the part were it says Mongoclient.connect() and the rest is done by logic, it displays now in the express and in postman as well.
const {MongoClient} = require('mongodb');
const express = require("express");
const app = express()
async function main() {
const uri = "mongodb+srv://dbUser1:<password>#movies.uxfxv.mongodb.net/Movies?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
let dbo = db.db("Movies");
dbo.collection("Movies").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
app.get("/", (req, res) => {res.json(result)})
db.close()
})
})
app.listen(4000, function() {
console.log("listening to port 4000)
}
main().catch(console.error)
Here is another way:
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const app = express();
const url = 'mongodb://localhost:27017';
const dbName = 'test';
const port = 3000;
app.listen(port);
// Type this in your browser to see db data: http://localhost:3000/
app.get('/', function(req, res) {
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(function(err) {
console.log("Connected to server.");
const db = client.db(dbName);
db.collection("books")
.find({})
.toArray(function(err, result) {
if (err) throw err;
client.close();
console.log("Done reading db.");
res.send(JSON.stringify(result));
});
});
});
I can't figure out why this gives the error.
If I remove the db.SendTodo from the code in controller.js it works fine but it seems like it is not working for exports.sendTodo in databaseConnect.js
databaseConnect.js File -
//Code
const mongo = require('mongodb');
let db = mongo.MongoClient
const assert = require('assert');
let url = "mongodb://127.0.0.1:27017/"
const express = require('express')
const bodyParser= require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
db.connect(url, function(err, client) {
if (err) {
console.log("Not Responding " + err);
}else {
console.log("Connection Established");
let database = client.db('todo_app_node');
let coll = database.collection("todos")
//Error is here
exports.SendTodo = (req, res) => {
console.log("Whoooo");
coll.insertOne(body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
next()
})
}
//Show The Result
coll.find({}).toArray(function(err, result) {
if (err) {
console.log(err);
}else if (result.length) {
//Responding to the requests
exports.item = result
}else {
console.log("A error occured");
}
client.close()
})
}
})
Router.js
const express = require("express")
const router = express.Router()
const bodyParser= require('body-parser')
const controler = require('./controller/controller.js');
const db = require('./controller/databaseConnect.js');
router.get("/", controler.renderPage);
router.post('/send', db.SendTodo)//Error is this line
router.get("/css/index.css", controler.cssFiles);
module.exports = router;
Your .SendTodo function needs a bit of work. Put next in its argument list, then use it correctly. Try this.
exports.SendTodo = (req, res, next) => { // add next to parameter list
console.log("Whoooo");
coll.insertOne(body, (err, result) => {
if (err) return next(err) // send your error to next()
console.log('saved to database')
return res.redirect('/') // don't use next() after redirect()
})
}
Here's documentation on error handling in express.
And, when your route handler completes the response to the incoming request, don't call next(); you're done.
the next() function being called is not in the args. So its throwin out the error.
In router :
router.post('/send', db.SendTodo,the_actual_function_to_called_next);
In controller: (add next so that its passed along from router)
exports.SendTodo = (req, res,next) => {
console.log("Whoooo");
coll.insertOne(body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
next()
})
}
I am trying to request data from a postgres database in node.js via a post request. Eventually this data will be sent a react frontend.
I am getting correct data from database but can't seem to return this data to app.js (I'm a bit of a node.js noob). I have two files app.js and db.js
Here is app.js
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors')
const db = require('./db')
const bodyParser = require('body-parser')
const middlewares = require('./middlewares');
const app = express();
app.use(cors());
app.use(morgan('dev'));
app.use(helmet());
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(bodyParser.urlencoded({ extended: false }))
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
next();
});
app.get('/api', (req, res) => {
res.send({ express: 'Server online' });
});
app.post('/layer', (req, res, next) => {
var layer = req.body.menu;
var geometry = db.layer(layer);
console.log(geometry);
res.set('Content-Type', 'application/json')
//const body = res.body()
});
app.use(middlewares.notFound);
app.use(middlewares.errorHandler);
module.exports = app;
Here is db,js
const { Pool, Client } = require('pg')
const connection = new Pool({
user: 'postgres',
host: 'localhost',
database: 'dbtemp',
password: 'password',
port: 5432,
max: 20,
connectionTimeoutMillis: 2000,
})
connection.connect(function(err) {
if (err) throw err;
});
connection.on('connect', () => {
console.log("connected to database on port: " );
});
module.exports = {
layer: function(layer) {
connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
if (err) {
return console.error('Error executing query', err.stack)
}
var geometry = result.rows[0].st_asgeojson;
console.log(geometry);
return result;
})
}
}
I am getting the correct data logged to console from db.js
Output:
Listening: http://localhost:5000
connected to database on port:
Promise { undefined }
connected to database on port:
{"type":"MultiLineString","coordinates":[[[1797202.15,5753380.18,0],[1797200.87,5753384.48,0],[1797198.16,5753393.62,0],[1797197.78,5753404.37,0],[1797200.38,5753428.48,0],[1797217.82,5753566.48,0],[1797225.98,5753623.6,0],[1797227.09,5753645.86,0],[1797225.98,5753665.52,0],[1797223.38,5753684.07,0],[1797213.95,5753717.71,0]]]}
How do I get query result to app.js and send to webpage (React front end). I'm guessing it needs a callback when data is ready?
You may want to consider using a promise or a callback
Promise approach
db.js
...
module.exports = {
layer: function(layer) {
return new Promise((resolve, reject) => {
connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
if (err) {
console.error('Error executing query', err.stack)
return reject(err);
}
var geometry = result.rows[0].st_asgeojson;
console.log(geometry);
return resolve(result);
})
})
}
}
app.js
...
app.post('/layer', async (req, res, next) => {
var layer = req.body.menu;
var geometry = await db.layer(layer);
console.log(geometry);
res.set('Content-Type', 'application/json')
//const body = res.body()
});
Callback approach
db.js
module.exports = {
layer: function(layer, cb) {
connection.query('SELECT ST_AsGeoJSON(geom) FROM nzta_centrelines', (err, result) => {
if (err) {
console.error('Error executing query', err.stack)
return cb(err)
}
var geometry = result.rows[0].st_asgeojson;
console.log(geometry);
return cb(null, geometry);
})
}
}
app.js
...
app.post('/layer', (req, res, next) => {
var layer = req.body.menu;
db.layer(layer, (err, geometry) => {
if (err) throw err;
console.log(geometry);
res.set('Content-Type', 'application/json')
//const body = res.body()
});
});
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);
});
};