Why I can't connect Mongodb server in Heroku? - reactjs

I want to develop ToDoApp with React and MongoDb. I created database in MongoDb Atlas and entegrated to my react. In local, everything is working but in heroku, I got error.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
let Todo = require('./todo.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb+srv://<MyUsername>:<MyPassword>#asnus-sql-5enaw.mongodb.net/todolist', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})
...
...
...
...
...
...
"eslintConfig": {
"extends": "react-app"
},
"proxy":"http://localhost:4000"
}
This is my app in heroku, you can see 'Failed to load resource: net::ERR_CONNECTION_REFUSED' error in console:
https://asnus-todolist.herokuapp.com
And if you want you can see my code in github:
https://github.com/sametsunman/ToDoList

Related

CORS enabled using Express but still getting CORS error

I am using React and Express. Here is my code in Express.
const express = require("express")
const bodyParser = require("body-parser")
const { connection } = require("./db/connection")
const user = require("./routes/user")
const product = require("./routes/product")
const rentalHistory = require("./routes/rental-history")
const cors = require("cors")
const app = express()
app.use(express.static(__dirname + "/upload"))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(cors())
app.get("/", async (req, res) => {
res.json({ message: "Carbon Copies Rest Api" })
})
app.use("/user", user)
app.use("/product", product)
app.use("/rental-history", rentalHistory)
module.exports = { app }
When I hit this link https://carbon-copies-restapi.herokuapp.com/image_1628058210309.jpeg on the frontend. It throws this CORS Error. Other routes work just fine
I had the same issue, i solved adding 'origin: true' in the cors configuration.
app.use(cors({
origin: true
}))

Issue connecting to token server with Firebase hosting

I am trying to deploy the Twilio video app to Firebase hosting. Everything works great, except when I try to connect to video conference it tells me the Twilio tokens are invalid.
I found that I need to set up google cloud functions to resolve this. How do you go about converting a server.js file to a cloud function?
Here is my code server.js code:
const express = require('express');
const app = express();
const path = require('path');
const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
require('dotenv').config();
const MAX_ALLOWED_SESSION_DURATION = 14400;
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKeySID = process.env.TWILIO_API_KEY_SID;
const twilioApiKeySecret = process.env.TWILIO_API_KEY_SECRET;
app.use(express.static(path.join(__dirname, 'build')));
app.get('/token', (req, res) => {
const { identity, roomName } = req.query;
const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret, {
ttl: MAX_ALLOWED_SESSION_DURATION,
});
token.identity = identity;
const videoGrant = new VideoGrant({ room: roomName });
token.addGrant(videoGrant);
res.send(token.toJwt());
console.log(`issued token for ${identity} in room ${roomName}`);
});
app.get('*', (_, res) => res.sendFile(path.join(__dirname, 'build/index.html')));
app.listen(8081, () => console.log('token server running on 8081'));
I'm thinking I can move that to the cloud functions index.js file and add the following to still connect to my .env file variables if I put the express function in here:
const functions = require('firebase-functions');
const config = functions.config();
// Porting envs from firebase config
for (const key in config.envs){
process.env[key.toUpperCase()] = config.envs[key];
}
To convert this to a Firebase cloud function, you need to remove server listeners and you have to setup a local Firebase environment to deploy and develop
Steps to convert cloud function
# Install firebase-tools
npm install -g firebase-tools
# Login and initialize project
firebase login
firebase init functions
# For local dev
firebase serve
# Deploy the function to cloud
firebase deploy
Your current code will look something like this after converting to cloud function
You can also make each routes into separate modules
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const path = require('path');
const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
require('dotenv').config();
const router = express.Router();
const MAX_ALLOWED_SESSION_DURATION = 14400;
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKeySID = process.env.TWILIO_API_KEY_SID;
const twilioApiKeySecret = process.env.TWILIO_API_KEY_SECRET;
app.use(express.static(path.join(__dirname, 'build')));
router.get('/token', (req, res) => {
const { identity, roomName } = req.query;
const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret, {
ttl: MAX_ALLOWED_SESSION_DURATION,
});
token.identity = identity;
const videoGrant = new VideoGrant({ room: roomName });
token.addGrant(videoGrant);
res.send(token.toJwt());
console.log(`issued token for ${identity} in room ${roomName}`);
});
router.get('*', (_, res) => res.sendFile(path.join(__dirname, 'build/index.html')));
// Your cloud function will be like : https://<region>-<appname>.cloudfunctions.net/twilioApp
exports.twilioApp = functions.https.onRequest(router);
Please read the official documentation here

Trying to serve a static txt file while using MERN stack

Im using the MERN stack + Heroku to deploy and want to host a static txt file at "myurl.com/file.txt".
My file.txt is in the client/build directory.
When I navigate to "myurl.com/file.txt" I get "Cannot GET /file.txt"
I know this is probably a newby question and a bit open ended, I have looked a bunch online but I'm struggling to figure this out. Thanks in advance!
Here is a code snippet of my server.js file.
If there is any other info you need pls ask!
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = "my_mongodb_uri"; // of course here I have my actual URI, I know its not secure, I'll change it before it goes public :P
mongoose.connect(uri, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true })
.then(connect => console.log('connected to mongodb'))
.catch(e => console.log('could not connect to mongodb', e))
const connection = mongoose.connection;
connection.once('open', () => { console.log("MongoDB database connection established successfully"); })
const matchesRouter = require('./routes/matches');
const usersRouter = require('./routes/users');
app.use('/matches', matchesRouter);
app.use('/users', usersRouter);
if(process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'));
}
app.listen(port, () => {
console.log(`Server is running on port: ${port}`)
});

React app deploying on heroku, not loading DB from mlab

When I run heroku local, app working as expecting.
On production, it's not loading anything from Mlab (remote mongoDb)
Here is it
https://react-bulletin.herokuapp.com/
Just showing static react file.
here is my server file
require('dotenv').config();
// Express Stuff
const express = require('express');
const app = express();
const cors = require('cors')
const path = require('path')
// Mongo Wrapper
const mongoose = require('mongoose');
// Supporting Libraries
const bodyParser = require('body-parser');
// Globals
const dbUrl = process.env.MONGODB_URI
const port = process.env.PORT
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useFindAndModify: false
});
app.use(cors())
app.use(bodyParser.json());
app.use('/', require('./Routes'));
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Running at http://localhost:${PORT}`);
I have no idea why is that.
Please any help.
PS
MONGODB_URI is added to heroku varibles.

socket.io react heroku 405

I have the following server file:
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = module.exports.io = require('socket.io')(server)
const PORT = process.env.PORT || 3231
const SocketManager = require('./SocketManager')
app.use(express.static(__dirname + '/../../build'))
io.on('connection', SocketManager)
server.listen(PORT, ()=>{
console.log("Connected to port:" + PORT);
})
And I am connecting it on the front end like so:
import React, { Component } from 'react';
import io from 'socket.io-client';
import Game from '../Game/Game';
import axios from 'axios'
const socketUrl = "/"
const socket = io(socketUrl)
But I keep getting this in my console:
Failed to load resource: the server responded with a status of 405 (Not Allowed)
I really am not sure what to change or set up to rectify what is an error.
My set up was not proper for the people that are having trouble with socketio connection with their backend from a react frontend. This worked for me:
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = module.exports.io = require('socket.io')(server, { origins: '*:*'})
const path = require('path')
// for prod dont use port #
const PORT = process.env.PORT || 3001
const SocketManager = require('./socketmanager')
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
io.on('connection', SocketManager)
server.listen(PORT, ()=>{
console.log("Connected to port:" + PORT);
})

Resources