How find endpoints of my heroku deployed nodejs app? - node.js

Below you can see my localhost nodejs api endpoint and its successfullyworking.
http://localhost:3000/api/user/login/
But after I deployed app in Heroku I cannot call that endpoint.
After deployed in the heroku I tried with this url
https://employee-management-app-001.herokuapp.com/api/user/login
Below you can see my server file
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const port = process.env.PORT || 3000;
const uri = 'mongodb+srv://user1:1234#cluster0.pkiw6x0.mongodb.net/comp3123_assignment1'
//const jwt =require('jsonwebtoken');
var cors = require('cors')
app.use(cors())
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Successfully connected to the database mongoDB Atlas Server");
}).catch(err => {
console.log('Could not connect to the database.', err);
process.exit();
});
app.use(express.json())
const usersRouter = require('./routes/users')
app.use('/api/user',usersRouter)
const employeesRouter = require('./routes/employees')
app.use('/api/emp',employeesRouter)
mongoose.connect(uri)
app.listen(port,()=> console.log("Server Started on Port "+port))
Can anyone helop me to solve thiss issue?

Related

Mongo DB not connecting to NodeJS after Heroku deployment

I've a MERN app (Mongo Express React Node) that works locally, and connects to my MongoDB database, getting data.
The React front-end works after I deploy it to Heroku, but Nodejs won't connect to MongoDB on Heroku.
The environment variables like MONGO_URI stored as Heroku config variables, works perfectly fine, yet it just won't connect to my MongoDB.
The Heroku logs shows the error message: DISCONNECTED FROM MONGO DB from my server.js file.
How can I solve this?
server.js file
const express = require("express");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
dotenv.config();
const authRouter = require("./routes/auth");
const blogRouter = require("./routes/blog");
const userRouter = require("./routes/user");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use("/api/auth", authRouter);
app.use("/api/user", userRouter);
app.use("/api/blog", blogRouter);
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const connect = () => {
mongoose
.connect(process.env.MONGO_URL,
{useNewUrlParser: true,
useUnifiedTopology: true,
useNewUrlParser: true})
.then(() => {
console.log("CONNECTED TO THE MONGO DB");
})
.catch((err) => {
console.log(err);
mongoose.disconnect(() => {
console.log("DISCONNECTED FROM MONGO DB");
});
})
};
app.listen(process.env.PORT || 8000, () => {
connect();
console.log("MONGO_URL", process.env.MONGO_URL);
console.log("PASSCODE", process.env.PASSCODE);
console.log(`LISTENING ON PORT ${process.env.PORT}`);
})
Your environment variable to connect to MongoDB database has to be MONGO_URI, not MONGO_URL.
Otherwise it won't work.

Express app on heroku throws authentication error on POST requests

The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})

heroku connecting to mongodb atlas only when node conected and running on vsCode

I create a web site with MERN stack and deploy it with heroku. the DB connected to mongodb atlas. work great locali but when i try to connect the DB with heroku its working only when my backend on vsCode connected to the DB.
the error notes is:
*Failed to load resource: net::ERR_CONNECTION_REFUSED
*Uncaught (in promise) Error: Network Error
at e.exports (createError.js:16:15)
at XMLHttpRequest.g.onerror (xhr.js:117:14)
this is my code:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const usersRouter = require("./routes/usersRout");
const authRouter = require("./routes/auth");
const carsRouter = require("./routes/carsRout");
const bizRouter = require("./routes/bizRout");
mongoose
.connect(
process.env.MONGODB_URI ||
"mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority"
)
.then(() => {
console.log("connected to mongo");
})
.catch((err) => {
console.log("faild to connect to mongo server", err);
});
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("noto-front/build"));
}
app.use("/api/users", usersRouter);
app.use("/api/auth", authRouter);
app.use("/api/cars", carsRouter);
app.use("/api/biz", bizRouter);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`connected on port ${PORT}`);
});
my config vars on heroku:
MONGODB_URI - mongodb+srv://reutudler:eJ53Guyvm7ySeMra#notodb.s9aba.mongodb.net/notodb?retryWrites=true&w=majority
NODE_ENV - production
what am i doing wrong?

Socket.io + node JS = Error during handshake: error code 500

I was working on Socket.io and node jS to develop a chat web app. It worked locally but I have faced many issues when I deployed my changes to Azure app service.
I am creating a secure connection on port 443. I have resolved other issues but I can't resolve this one.
This the error I'm getting in console on client side.
WebSocket connection to 'wss://mydomain/socket.io/?EIO=3&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 500
This is how I'm connecting on server side
var socket = io.connect("https://mydomain:443", {transports: ['websocket'], secure: true, port: '443'});
and this is my server.js code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
const cors = require('cors')
const https = require('https');
const fs = require('fs');
var options = {
pfx: fs.readFileSync('certificate.pfx'),
passphrase: 'password'
};
app.use(cors());
var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*');
client.set('transports', ['websocket']);
server.listen(443);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }, (err, db) => {
if (err) {
throw err;
}
console.log('MongoDB connected');
chatSocket(db, client);
});
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);
const port = process.env.PORT || 5000;
app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
I have checked the logs, there are no errors there.

nodejs cant connect to mongodb using mongoose

so all my applications were working just fine using mongoose, all of a sudden they all stopped. i cant connect to my database. however my deployed apps using mongoose databases work fine, but i cant access to any database using my local computer. here is a test server ive written. can someone help me whats happening.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const app = express();
app.use(express.json())
const db = require('./keys').mongoURI;
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('connected'))
.catch(err => console.log(err))
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server running'))
module.exports = {
mongoURI: 'mongodb+srv://ertemishakk:<password>#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majority'
}
Terminal:
server running
MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout._onTimeout (/Users/ishakertem/Desktop/test/node_modules/mongodb/lib/core/sdam/server_selection.js:308:9)
at listOnTimeout (internal/timers.js:536:17)
at processTimers (internal/timers.js:480:7) {
name: 'MongoTimeoutError',
}
You should check your
bindIp : [public_ip]
option in
mongod.conf
file.
It should be pointed out to public IP of that system on which MongoDB is running.
You can use 0.0.0.0 for debuging only, because it is exposed One.
[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU]
You Can Follow This Code I hope solved your problem
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const app = express();
app.use(express.json())
//Remove <password> and provide DB password
/**
* Example: mongodb + srv: //ertemishakk:123#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majorit
*/
mongoose.connect('mongodb+srv://ertemishakk:<password>#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majorit', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('connected'))
.catch(err => console.log(err))
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server running'))

Resources