I'm trying to make request to a postgreSQL DB being accessed by a Node + Express server that I've deployed on Heroku. This is the error im getting when running 'heroku logs': Error: connect ECONNREFUSED 127.0.0.1:5432, along with a couple other errors. I'm using axios on the frontend to make request.
Here is my server.js file:
// express
const express = require('express');
// environment variables
require('dotenv').config();
// data base connector
const db = require('./db');
// cors
const cors = require('cors');
// express instance
const app = express();
// use cors
app.use(cors());
// attach data to req.body
app.use(express.json());
// get all articles
app.get('/api/v1/articles', async (req, res, next) => {
try {
// query database
const results = await db.query('SELECT * FROM articles;');
// send results
res.status(200).json({
results: results.rows
});
// handle error
} catch (err) {
next(err);
}
});
// get individual article
app.get('/api/v1/articles/:id', async (req, res, next) => {
try {
// query database
const article = await db.query(`SELECT * FROM articles WHERE id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
article: article
});
// handle error
} catch (err) {
next(err);
}
});
// get article's comments
app.get('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// query database
const comments = await db.query(`SELECT * FROM comments WHERE article_id = $1;`, [req.params.id]);
// send back data
res.status(200).json({
comments: comments
});
// handle error
} catch (err) {
next(err);
}
});
// add comment
app.post('/api/v1/articles/:id/comments', async (req, res, next) => {
try {
// post comment in database
const comment = await db.query(`INSERT INTO comments (article_id, author, text)
VALUES ($1, $2, $3) returning *;`, [req.body.article_id, req.body.author, req.body.text]);
// send comment back
res.status(201).json({
comment
});
// handle error
} catch (err) {
next(err);
}
})
// listen
const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Server now listening on PORT ${port}`);
});
I'm supposedly connected to my DB with the pg library, and the Pool gets the credentials from an .env file. I'm able to connect to the DB within pgAdmin and write queries, make tables etc.
Any help greatly appreciated
Check your database connection configuration. The error shows that it tries to connect to PostgreSQL on 127.0.0.1 which is LOOPBACK ip address. This means that is trying to access the server on your machine. You need to configure the connection by specifying the correct address for the server where PostgreSQL is running
Related
I understand that we need to use asynch and await while connecting db since models are loading before db connection happening so i have used and call the function in server.js Please look into my code and help me.
Connection.js
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
console.log(process.env.DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
//useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
Server.js
const express = require('express');
const dotEnv = require('dotenv');
const { urlencoded } = require('express');
const cors = require('cors');
const dbConnection = require('./database/connection');
dotEnv.config({path:'./.env'});
const app = express();
// Database connection
// cors
app.use(cors());
app.use(express.json());
dbConnection();
app.use('/api/v1/domain', require('./routes/domainRoutes') );
app.get('/', (req, res, next)=>{
res.send("Hello From node aPI server");
});
// request payload middleware
app.use(express.json);
app.use(urlencoded({extended:true}))
const PORT = process.env.PORT || 3000;
app.listen(PORT, ()=>{
console.log(`Server Listen on port ${PORT}`);
});
// error handling middle ware
app.use(function(err, req, res,next){
console.error(err.stack)
res.status(500).send({
status: 500,
message:err.message,
body:{}
})
});
DomainService.js
const Domain = require('../database/models/DomainModel');
module.exports.createDomain = async (serviceData) => {
try {
let domain = new Domain({...serviceData})
return await domain.save();
} catch (error) {
console.log("Soemthing wrong: Service : Create Domain ", error);
throw new Error(error);
}
}
you can find full code here
https://github.com/vlpreddy/node-express-rest-api
I am trying to develop rest api's using nodeJs, tried to connect with mongoddb using mongoose. I am getting this timeout error since 2 days, i tried most of the solutions in the internet including using await and async.
So can someone please look into my code and help me.
Since I was stupid enough, I haven't installed mongodb in my system, so it was not connecting obviously. But I felt like it suppose to throw an error like
dude there is no mongodb in your system, how the heck do you think you
can create database and store the collections.
Any how people who are coming here with same error but a different reason can utilise following code and connect database using async and await functions as new version can load models with out even caring whether database is connected or not.
**database/connection.js**
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
module.exports = async () => {
//console.log(DB_URL);
await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{
console.log("Database Connected");
}).catch (error => {
console.log("Database connectivity Error", error);
});
}
you can import in any page and call the variable as a function
since it returns a promise function which is written below.
const dbConnection = require('./database/connection');
dbConnection();
I am following a tutorial online to make a simple CRUD node/express/mongo application. I can get this code to connect to the data base fine, but when I try to submit a quote to be added to the database, the console simply logs the data I've entered, and the data never actually gets added to the database. If anyone could help me to understand why this isn't working, I'd appreciate it.
A possible issue may be, in MongoDB atlas my project is called testeru, my database is called test, and my collection is called quotes. I'm not sure if I improperly referenced this data?
I am running this on local host and I did whitelist my IP address in Atlas.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//mongodb
const MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb+srv://OBSCURED:OBSCURED#cluster0.izcbs.mongodb.net/test?retryWrites=true&w=majority', { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
const db = client.db('test')
const quotesCollection = db.collection('quotes')
// app.use{}
// app.get{}
app.post('/quotes', (req,res) => {
quotesCollection.insertOne(req.body)
.then(result => {
console.log(result)
})
.catch(error => console.error(error))
})
// app.listen{}
})
.catch(error => console.error(error))
//Body parser
app.use(bodyParser.urlencoded({extended:true}))
app.listen(3000, function() {
console.log('Listening on 3000');
})
//Get request:
app.get('/', (req,res) => {
res.sendFile(__dirname + '/index.html');
})
//CREATE
app.post('/quotes', (req, res) => {
console.log(req.body)
})
I have a tiny express server that I want to use to get some data from a collection in my database:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const PORT = 3000;
const MONGO_URI = 'mongodb://127.0.0.1:27017/test';
async function myReport(schoolId) {
const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect()
console.log("Hello!"); // This is never ran unless I remove "await" from the above line :S
const db = client.db();
const result = db.collection('states').find({}).map((a, b, c) => {
console.log("This never runs", a, b, c);
return "asdf";
});
return result;
} catch (err) {
console.log("ERROR", err);
}
client.close();
};
// Hoisting server
app.get('/api/reports/states/:id', async function (req, res, next) {
const report = myReport(req.params.id)
res.json(report); // {}
});
app.listen(PORT, (err) => {
console.log(`reporting listening in`, PORT);
});
I really don't know what I'm doing wrong here. Tried using .each, toArray and I'm not able to get the actual results as a list.
I've been following these docs: https://mongodb.github.io/node-mongodb-native/3.6/api/Cursor.html
Any idea what I'm doing wrong?
As per your saying:
await client.connect()
console.log("Hello!"); // This is never ran unless I remove "await" from the above line :S
I think connection is not establishing. I tried your code with a little bit modification. I created a cluster on Atlas Mongodb and used its URI as a connection string.
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
const PORT = 3000;
const MONGO_URI = 'mongodb+srv://<username>:<password>#cluster0-oqotc.mongodb.net/<dbname>?retryWrites=true&w=majority';
const getListings = async () => {
const client = new MongoClient(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect()
console.log("Hello!"); // This will print now :-)
const listings = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({});
return listings;
} catch (err) {
console.log("ERROR", err);
}
client.close();
};
// Hoisting server
app.get('/api/get-listings', async function (req, res, next) {
const report = await getListings()
res.json(report);
});
app.listen(PORT, (err) => {
console.log(`reporting listening in`, PORT);
});
You need to change username, password and dbname with your ones.
Note: While using Atlas Mongodb Cluster, if you are getting connection error, you need to whitelist your ip as well.
Hope it will help you. Thanks
You defined myReport as an asynchronous function which returns a promise. Add toArray() back into your code and then get your report like this
app.get('/api/reports/states/:id', async function (req, res, next) {
myReport(req.params.id).then(report => {
res.json(report);
});
});
Because its the call to res.json is also in an asynchronous function I think you can also do
app.get('/api/reports/states/:id', async function (req, res, next) {
const report = await myReport(req.params.id);
res.json(report);
});
I have made a basic fullstack website using mssql and express. Originally the get routes worked but after implementing the post route they have stopped.
I believe I am receiving a cors error which is.
Proxy error: Could not proxy request /admin-view-users from localhost:3000 to http://localhost:5000/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
my server.js
const express = require("express");
const sql = require("mssql");
var cors = require("cors");
const path = require("path");
var bodyParser = require("body-parser");
const port = process.env.PORT || 5000;
const app = express();
app.use(cors());
app.use(express.json());
const config = {
user: "sas",
password: "Mypassword456",
server: "DEVSQL_2014", // You can use 'localhost\\instance' to connect to named instance
database: "TestDBWebsite"
};
//AdminView users just pulls the users from the database
app.get("/admin-view-users", cors(), function(req, res) {
// connect to your database
sql.connect(config, 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 Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/admin-view-users", function(req, res) {
// connect to your database
sql.connect(config, 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 Users2 ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
res.end();
});
});
});
app.get("/user-questions", function(req, res) {
// connect to your database
sql.connect(config, 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 Questions ", function(err, recordset) {
if (err) console.log(err);
// send records as a response
res.json(recordset);
});
});
});
//
var jsonParser = bodyParser.json();
app.use(express.bodyParser());
app.post("/admin-Add-Users", jsonParser, function(request, response) {
var email = req.body.email;
var password = req.body.password;
var request = new sql.Request();
// query to the database and get the records
console.log(email, password); // your JSON
// echo the result back
console.log(request.body);
request.query(
"insert into Login (email, password) values ('" +
email +
"','" +
password +
"')",
function(err, recordset) {
if (err) console.log(err);
}
);
response.send({ message: "Success" });
});
app.listen(port, () => `Server running on port ${port}`);
I have included "app.use(cors());" which I assumed woudl resolve this but it has not.
Please advice if you can .
The first thing that comes up to my mind is the double use of CORS.
You are putting it uptop in the middleware stack and then calling it again in here:
app.get("/admin-view-users", cors(), function(req, res) {
Please try using this only once:
https://www.npmjs.com/package/cors
I am trying to connect to atlas mongo db using node js. But getting the error TypeError: Cannot read property 'db' of null I have created the cluster at atlas and given complete rights to user aayushg and also created a db 'test'
index.js
const express = require('express')
const bodyParser= require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
const MongoClient = require('mongodb').MongoClient;
// replace the uri string with your connection string.
const url = "mongodb+srv://aayushg:<aayushg18>#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect((err, database) => {
db = database.db("test")
app.listen(3000, function () {
})
app.get('/', (req, res) => {
//res.send('PDP')
res.sendFile(__dirname + '/index.html')
})
app.post('/quotes', (req, res) => {
db.collection('devices').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log('saved to database')
res.redirect('/')
})
})
})
SCREENSHOT OF CMD
So, the error was related to the credentials you are providing with the help of if(err) throw err you can see the error is regarding the credentials. Now, you have to add correct credentials it will work fine. you are using <aayushg18> instead of aayushg18 Thanks.
I have got your problem. You connection uri is not in correct format. Do not use <> sign when you input your password. Replace <aayushg18> by aayushg18 like following:
const uri = "mongodb+srv://aayushg:aayushg18#cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";