I'm trying to establish a connection between my node express server and a Firebird database from an external server. I'm using this node-firebird library
This is my code on my index.js:
require("dotenv").config(); //Environment variables
const express = require("express");
const morgan = require("morgan");
const Firebird = require('node-firebird');
//Express Initilization
const app = express();
//MORGAN Configuration
app.use(morgan("dev"));
app.use( express.json() );
app.use( express.static("public") );
const options = {
"host" : 'externalddns.ddns.net',
"port" : 3050,
"database" : 'c:/database/databaseName.fb',
"user" : 'SYSDBA',
"password" : 'masterkey',
"lowercase_keys" : false,
"role" : null,
"pageSize" : 4096
};
Firebird.attach(options, function(err, db) {
if (err) {
throw err;
}
const query = "SELECT * FROM MYTABLE";
db.query(query, function(err, result) {
if(err){
console.log(err);
}
console.log(result);
// Close the connection
db.detach();
});
});
app.listen(process.env.PORT, () => {
console.log("Server running on port " + process.env.PORT);
});
I already open 3050 port on the external site router and firewall. The connection is working because if I select another path for the database and I do Firebird.create(.....) the database file is being created on the path specified. But I'm not getting any response from the console.log(result) on the db.query, not even an error. The only msg on the console is Server running on port MYPORT.
I can force an error if I change the query to select for a table that doesn't exist in the db. So the code is working but when it seems to be everything ok I don't get any response.
The database file is ok because is working for another service.
Is it possible that something on my pc is blocking the response? Like firewall or something. Any help would be appreciated.
I already know where the problem was. That library was for firebird 2.5+ version and my firebird server version was 2.1. -_-
Related
I am new to fullstack development and I want to deploy a project that will be used on the same network by different users. I have used angular for the front-end and node/express and MySQL for the backend. Before proper deployment, for testing purposes, I am accessing my application from another computer that is on the same network. The application, however, is throwing an error when I try to login.
VM12:1 POST http://localhost:3000/auth net::ERR_CONNECTION_REFUSED
Here's my backend code:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysqlConnection = require('./connection');
const routes = require('./routes');
const http = require('http');
const path = require('path');
var app = express();
app.disable('x-powered-by');
app.use(express.static(__dirname + '/dist'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
app.use(cors());
app.use(bodyParser.json());
app.use(routes);
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port, '0.0.0.0', () => console.log(`Running on port ${port}`));
routes.js
router.post("/auth", (req, res) => {
var email = req.body.email;
var password = req.body.password;
var accessBasic = "Basic";
var accessPremium = "Premium";
mysqlConnection.query("SELECT * FROM authorization WHERE email = ? AND password = ?", [email,
password], (err, results) => {
if(!err)
{
var myJSON = JSON.stringify(results);
var check_email = myJSON.search(/email/i);
var check_password = myJSON.search(password);
var check_access = myJSON.search(accessBasic);
var check_access2 = myJSON.search(accessPremium);
if ((check_email != -1) && (check_password != -1) && (check_access != -1))
{
res.send("Successfully Authorized to Basic Access");
}
else if ((check_email != -1) && (check_password != -1) && (check_access2 != -1))
{
res.send("Successfully Authorized to Premium Access");
}
else
{
res.send("Authorization failed");
}
}
else
{
console.log("Connection to authorization failed: " + err.message);
}
})
})
I have allowed incoming connections in my firewall and done everything but, couldn't find the reason why my endpoint is refusing to connect while trying to connect on device other than my system on the same network. I don't know what's wrong. Anybody has any idea what am I doing wrong? I have hosted my application on my system and accessing it from another on the same network.
EDIT: Since, this question has gained quite a lot of views, I would like to mention that I didn't change any of the firewall settings as mentioned above. All the default firewall settings of the Windows OS were used. I just deployed the app and ran it.
ANSWER: I was having an issue on the front-end. I was targeting localhost instead of the IP address of the system that the app was hosted on. See my answer below for the details.
For anyone who is going to see this in future. I was having an error on my front-end. Instead of calling http://localhost:3000/name-of-my-api-endpoint, I changed the localhost to the IP address of my system and then ran ng build --prod again in order to make new static files and serve them from node.js.
I have experienced the same issue with MongoDB
I have found out that the problem was my MongoDB wasn't connected to my localhost and the issue was related to tokens and authentication.
So I went to my terminal on my backend folder and ran the command -
npm install dotenv --save
Then I created my .env file located in my backend folder
and added the following commands
PORT=3000 APP_SECRET="RANDOM_TOKEN_SECRET"
MONGODB="mongodb+srv://youruser:yourpassword#cluster0.k06bdwd.mongodb.net/?retryWrites=true&w=majority"
Then called it in my app.js file
const dotenv = require("dotenv");
dotenv.config();
mongoose.connect(process.env.MONGODB,
{ useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB!'))
.catch(() => console.log('Failed to connect to MongoDB !'));
module.exports = app;
Finally I have added it in my backend/controllers/user.js
const token = jwt.sign(
{userId: user._id},
process.env.APP_SECRET,
{expiresIn: '24h'});
res.status(200).json({
userId: user._id,
token: token
});
You can access your app in the same network from your #IP not from localhost (127.0.0.1) change it to 192.168.1.X (your local #IP address) and make sure to changed it in your .env file.
I've managed to get my Node.js app working properly with my Heroku Postgres database when the node application is deployed to Heroku. However having to deploy to heroku each time I make a code change is a bit arduous and I'd rather be able to develop locally and connect to the database from my local app.
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
The above article doesn't really describe how this is done, I'm not exactly sure what I need to do.
If I attempt to run my app locally and access an endpoint that queries my database I get
Error Error: connect ECONNREFUSED 127.0.0.1:5432
Whereas if I access the same endpoint from my heroku deployed app it works correctly.
Here's my app
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000;
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
express()
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/users', async (req, res) => {
try {
const client = await pool.connect();
const result = await client.query('SELECT * FROM users');
const results = { 'results': (result) ? result.rows : null};
console.log(results);
res.status(200).json(results);
} catch (err) {
console.error(err);
res.send("Error " + err);
}
})
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
I think you need to update the the process.env.DATABASE_URL on your local machine. From the error, it looks like the DATABASE_URL refers to localhost while you want to use the db hosted on Heroku.
I understand that you only want to use the remote db only. The error says you're unable to connect to 127.0.0.1:5432. This is the IP address of localhost, not the remote database. Your code is trying to connect to 127.0.0.1:5432 for some reason while it should be trying to connect to the remote db.
Did you use the dotenv to access process.env.DATABASE_URL ?
You need dotenv.config(); worked for me.
Actually i'm new to react and node and i was trying to make a simple NodeJS server which return some data from MySQL Database but i'm having some issues with the back-end part.
Actually i've installed NodeJS in another computer and followed this guide to deploy it.
Then in my React-Native app i just do simple fetch call to the NodeJS with the ip of the computer where the back-end part is installed till here all work fine and even from my personal computer i can get the data from NodeJS server but i face the issue when after loading data in React-App i kill that app and then i reopen it after that seems the server just die and i have to restart it with command 'node myfile.js'
After killing the app, NodeJS server is impossible to reach from any device and in browser after some minutes of load just return 'PAGE DOESN'T WORK ERR_EMPTY_RESPONSE'
Here is routes.js file located in another PC
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'block',
database : 'mydb'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/prenotazioni', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query("SELECT Data, Importo_Doc FROM tabella_pagamenti", function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Vai su http://localhost:3000/prenotazioni per vedere i dati.');
});
While method in my react-app where i call fetch is the following
GetData = () => {
return fetch('http://192.168.100.160:3000/prenotazioni')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
I am trying to connect my node.js game to a MongoDB cluster so that I can store username and passwords. I already have the a mock DB stored locally using express + socket.io. I am trying to set up MongoDB atlas to store the usernames + passwords so that when the local host closes, the data won't disappear.
I've tried the following Developing A RESTful API With Node.js And MongoDB Atlas word for word. When I test my connection if it was successful, I enter on terminal:
node app.js
My server starts as expected and prints server started. From this tutorial, I should either see an error or a successful connection message. However, when I start the server, I don't see either. I am having trouble debugging this because I am not getting any response at all.
Here is the beginning of my app.js file for context.
// Express code
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var MongoClient = require('mongodb').MongoClient;
const CONNECTION_URL = *uri here*
const DATABASE_NAME = "bunnyCrossing";
var timeRemaining;
// If query is '/' (nothing)
app.get('/',function(req,res){
res.sendFile(__dirname + '/client/index.html');
});
// If query is '/client'. Client can only request things from client folder
app.use('/client',express.static(__dirname + '/client'));
// replace the uri string with your connection string.
var database, collection;
app.listen(3000, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("people");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
});
// Server starts listening on port 2000
serv.listen(2000);
console.log("Server started");
I should see when I run node app.js:
server started
Connected to `bunnyCrossing`!
But I just see:
server started
Either app.listen is not being called or you must hit localhost:3000 to invoke the callback to connect to mongo database.
Either remove serv.listen or add a callback to serv.listen as such and remove app.listen.
serv.listen(2000, function(err) {
if (err) console.log(err);
else {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
collection = database.collection("people");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
}
})
I have following test code to run mongodb along with node.js while creating rest api
MONGO.JS
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/smartRideDb');
// create instance of Schema
var mongoSchema = mongoose.Schema;
// create schema
var userSchema = {
"id" : String,
"email" : String,
"password" : String
};
// create model if not exists.
module.exports = mongoose.model('user',userSchema);
index.js is defined as
var mongoOp = require("./models/mongo");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
app.use('/' , router);
var port = process.env.PORT || 3000;
/**
*
*
*
*/
// Generic error handler used by all endpoints.
function handleError(res, reason, message, code)
{
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
/**
*
*
*
*/
router.get("/",function(req,res)
{
res.json({"error" : false,"message" : "Hello World"});
});
//route() will allow you to use same path for different HTTP operation.
//So if you have same URL but with different HTTP OP such as POST,GET etc
//Then use route() to remove redundant code.
router.route("/users").get(function(req, res)
{
var response = {};
mongoOp.find({},function(err,data)
{
if(err)
{
response = {"error" : true,"message" : "Error fetching data"};
}
else
{
response = {"error" : false,"message" : data};
}
res.json(response);
});
});
app.listen(port);
console.log("Listening to PORT " + port);
When i run i get this error
Muhammads-MBP:Api Umar$ node index.js
Listening to PORT 3000
/Users/Umar/Desktop/Projects On List Data/Creative Studios/School Ride/Api/node_modules/mongodb/lib/server.js:242
process.nextTick(function() { throw err; })
^
Error: connect ECONNREFUSED 127.0.0.1:27017
at Object.exports._errnoException (util.js:890:11)
at exports._exceptionWithHostPort (util.js:913:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)
Why is mongodb not gett
You may want to try to ensure the MongoDB has properly setup first by following
MongoDB is installed successfully (OSX guide here)
Run mongod in terminal after installed to run the MongoDB
Run mongo in another terminal, and you should be able to see something similar.
.
MongoDB shell version: 3.2.4
connecting to: test
Try calling the connection to mongo before app.listen, mongoose open a pool of connections by default for attend the requests
mongoose.connect('mongodb://localhost/dbname', function(err) {
if (err) throw err;
app.listen(port);
console.log("Listening to PORT " + port);
});
Most common troubleshooting steps:
Configured localhost incorrectly somewhere, so try changing your connection string to mongodb://localhost:27017/smartRideDb.
Check if mongod is running at that port.
Check if some other process is using that port.