I am trying to deploy my nodejs API app for sometime to google cloud platform. Unfortunately it errors out saying this:
I do have the app.yaml file set with these commands
runtime: nodejs
env: flex
And this is the start file that I am trying to deploy
const express = require('express');
const mysql = require('mysql');
var bodyParser = require('body-parser');
const db = mysql.createConnection({
host : '35.230.**.**',
user : 'root',
password : '*********',
database : 'sale*******er'
});
//Connect
db.connect((err) => {
if(err){throw err;}
// console.log('Connected to Sales Tracker database!');
})
const app = express();
const port = process.env.PORT || 8080
app.use('/backend', backend);
app.listen(port, () => {
// console.log('Server started on port 3000');
});
Found an answer from another post
var connection = mysql.createConnection({
host : 'ip_address',
user : 'root',
password : 'password',
database : 'database_name'
socketPath: “/cloudsql/projectName:zone:instance-name”
});
https://stackoverflow.com/a/49169561/3826733
Related
I am getting the below error when I am trying to establish a database connection in my node js application using sequelize
C:\Users\user123\Desktop\project\node_modules\tedious\lib\token\token-stream-parser.js:24
this.parser = _stream.Readable.from(_streamParser.default.parseTokens(message, this.debug, this.options));
^
TypeError: _stream.Readable.from is not a function
I am in initial stage of creating an application. Where I have just tried to create a database connection, for which I have created three files
index.js
var dotenv = require("dotenv").config().parsed;
var customEnv = require("custom-env");
customEnv.env("development").env();
var express = require("express");
const helmet = require("helmet");
var cookieParser = require("cookie-parser");
const app = express();
app.use(helmet());
app.use(cookieParser());
require("./db.js");
httpserver = require("http").createServer(app);
httpserver.timeout = 0;
httpserver.listen(3457, async () => {
connectedEmitter.on("connectedDbs", () => {
console.log(` ----- SERVER LISTENING ON PORT `);
});
});
db.js
const Sequelize = require('sequelize');
const eventEmitter = require('events');
global.connectedEmitter = new eventEmitter()
global.sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: 1433,
dialect: process.env.DB_DIALECT,
ssl: false,
dialectOptions: {
ssl:false
},
logging:false,
pool: {
max: 20,
min: 0,
idle: 30000
}
});
sequelize.authenticate().then(() => {
console.log(`${process.env.DB_NAME} - Connection has been established successfully.`);
global.connectedEmitter.emit('connectedDbs')
}).catch((err) => {
console.error(' - Unable to connect to the database:', err);
});
.env (I am giving dummy credentials as I cannot provide original credentials)
# ################################## Database Credentials ##############################################
DB_NAME=mydb
DB_USER=username
DB_PASS=password
DB_HOST=hostname
DB_DIALECT=mssql
Can anyone please tell me why am I getting the error mentioned. Where have I made the mistake in setting the database connection. Please help.
I also faced this issue. Turns out tedious had issues with node versions below 12, and my production app service was running on node 10.
GitHub link that mentions this
I was trying to deploy my Express + React application to Heroku. Heroku connected successfully with my Github account, then clicking "Deploy Branch" led to "Your app was successfully deployed". But when I went to view my website, it showed:
"Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details".
Here are my logs:
Starting process with command `npm start`
> myproject# start /app
> node backend/index.js
My project SQL server listening on PORT 4000
/app/backend/index.js:22
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
And the index.js which connects to MySQL:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /my-project to see my project')
});
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/my-project', (req, res) => {
connection.query(SELECT_ALL_FACTS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
const SELECT_ALL_FACTS_QUERY = 'SELECT * FROM `my-project`.`my-table`;';
app.listen(4000, () => {
console.log('My project SQL server listening on PORT 4000');
});
What did I do wrong and how could I deploy it?
I think in the below code the localhost should not be used, the localhost will not work in deployment.
const pool = mysql.createPool({
connectionLimit: 10,
//here
host: 'localhost',
user: 'root',
password: 'myjs123#',
database: 'my-project',
debug: false
});
And another mistake I found is you should use an environment variable to store
port numbers. In production, the port number is assigned by Heroku, if not assigned you
can assign. So your code should be
let port=process.env.PORT||4000
app.listen(port, () => {
console.log(`App running on port ${port} `);
});
you need to add (add-ons) to your heroku account
and connect it to your app.
For example, you can use (JAWS_DB mysql)
By having the following code in your connection:
// import the Sequelize constructor from the library
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
// when deployed on Heroku
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
// localhost
sequelize = new Sequelize(process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
}
module.exports = sequelize;
It passed this stage after I removed if (err) throw err;, still not sure why this happened.
Nithin's answer was taken into account too.
the same errorhappened to me while i was trying to connect to heroku cli and i jus read the heroku config for proxy and that was the case. problem solved by configuring the http and https proxy like
set HTTP_PROXY=http://proxy.server.com:portnumber
or set HTTPS_PROXY=https://proxy.server.com:portnumber
I have looked around for a solution, but I can't seem to figure this out. What I'm trying to do is make POST/GET requests to a PostgreSQL database from an Express server.
main.js:
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port, () => {
console.log(`Server is running on localhost:${port}`);
});
server.on('error', onError);
server.on('listening', onListening);
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var indexRouter = require('./routes');
var app = express();
app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
module.exports = app;
routes.js (Handling the api requests)
router.post('/api/post/userprofiletodb', async (req, res, next) => {
console.log(req);
const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified];
// ON CONFLICT DO NOTHING - prevents the user profile from being stored in db twice
await pool.query(`INSERT INTO users(username, email, email_verified, date_created)
VALUES($1, $2, $3, NOW() )
ON CONFLICT DO NOTHING`, values,
(q_err, q_res) => {
if (q_err) return next(q_err);
console.log(q_res);
res.json(q_res.rows);
})
})
router.get('/api/get/userprofilefromdb', async (req, res, next) => {
console.log(req);
const email = String(req.query.email);
await pool.query(`SELECT * FROM users WHERE email=$1`, [email],
(q_err, q_res) => {
if (q_err) return next(q_err);
res.json(q_res.rows);
})
})
db.js:
const { Pool } = require('pg');
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydb',
password: 'mypassword',
post: 5432
});
module.exports = pool;
React code (Action Creators for Redux):
export const setDbProfile = (profile) => async(dispatch) => {
const response = await axios.post('http://localhost:8000/api/post/userprofiletodb', profile);
dispatch({ type: SET_DB_PROFILE, payload: response.data });
console.log(response);
history.replace('/');
}
export const getDbProfile = (profile) => async(dispatch) => {
const data = profile;
console.log('getDbProfile', profile);
const response = await axios.get('http://localhost:8000/api/get/userprofilefromdb',
{
params: {
email: data.profile.email
}
}
)
dispatch({ type: GET_DB_PROFILE, payload: response.data });
history.replace('/');
Here is my thought process:
- I have my Express server set up on http://localhost:8000 and my React application is running on http://localhost:3000 (I have already included a proxy in the package.json file).
- When the action creator is called, it first does a post request to http://localhost:8000 where my Express server is on.
- The Express server sees this and makes a request to the PostgreSQL database stored on localhost: 5432.
However, I'm getting this error....
POST /api/post/userprofiletodb 500 182.558 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
GET /api/get/userprofilefromdb?email=dasfdfasfdf#gmail.com 500 52.541 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
I think there may be an issue with my PostgreSQL database. How I set that up is by opening up SQL Shell (psql) and did the following:
- CREATE DATABASE mydb;
- \c mydb
- CREATE TABLE users(...);
- CREATE TABLE posts(...);
- CREATE TABLE comments(...);
Not too sure how I could solve this... Any guidance would be greatly appreciated! Cheers.
UPDATE:
When I run the command
netstat -na
I do not see, 127.0.0.1.5432 listed at all... Does this mean my database is just not setup properly?
Running SQL Shell (psql)
x-MacBook-Air:~ x$ /Library/PostgreSQL/12/scripts/runpsql.sh; exit
Server [localhost]:
Database [postgres]:
Port [5000]: 5432
Username [postgres]:
psql: error: could not connect to server: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Press <return> to continue...
I'm trying to connect to my MongoDB Atlas database, but it's not working, and I can't seem to figure out why.
I've made sure I don't use illegal characters in my username and password, I've tried different connection strings. I've tried turning off my firewall.
server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
const db = require("./keys").mongoURI;
mongoose.connect( db, { useNewUrlParser: true } )
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
keys.js
module.exports = {
mongoURI: "mongodb+srv://username:password#mernauth-lksvn.mongodb.net/test?retryWrites=true&w=majority"
};
I replaced the username and password in the connection string with the real username and password.
EDIT: SOLUTION
Even though I used both my IP address and the default IP address MongoDB Atlas suggested for me, neither worked. I guess I didn't have a valid IP address, so once I opened the database to all IP addresses, it worked!
The flowing code successfully connects mongoose with the mlab database on localhost and Heroku. But it's not working on Namecheap node js Server.
const express = require("express");
const mongoose = require("mongoose");
const port = parseInt(process.env.PORT, 10) || 3000;
const server = express();
mongoose.connect("mongodb://#ds213645.mlab.com:13645/techblog", {
useNewUrlParser: true,
auth: {
user: "user",
password: "pass"
}
});
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
name: String,
email: String
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
server.get("/test", async (req, res) => {
const user = new User({ name: "SomeName", email: "your#email.com" });
const userData = await user.save();
res.send(userData);
});
server.get("/", async (req, res) => {
res.send("working");
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on ${port}`);
});
When I hit the root('/') route it works perfectly on Namecheap server but when I hit test('test') route it response 'Incomplete response received from application' after a long time. So what is the way to connect mongoose with the database on Namecheap shared hosting?
Issue solved.
The problem was Namecheap. Namecheap blocked outgoing request on port 13645. After contacting them they opened outgoing request on port 13645
Contact namecheap support and ask them to open the ports below
ports:
27017
3000
443 and
80
at the first is used in local or MLAB if is MLAB try the same
mongoose.connect(MONGO_URI);
mongoose.connection
if used the MongoDB in local try to run the mongo server from go to the location
C:\Program Files\MongoDB\Server\4.0\bin and run mongo then run Mongod after then try to run the project enter image description here
"//"name user and password
: MustName_user:password //#ds213645.mlab.com:13645/techblog", {