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.
Related
I have a config that starts the server. I am making my project on typesript, do I need to typing this file? Do configs need to be typing or can they be left as they are?
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
if (process.env.NODE_ENV === "development") {
console.log("in development.");
} else {
console.log("in production.");
}
/* App Config */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "../dist")));
/* Server Initialization */
app.get("/", (req, res) => res.sendFile("index.html"));
var port = process.env.PORT || 3000;
app.listen(port, () =>
console.log(
`Server initialized on: http://localhost:${port} // ${new Date()}`
)
);
I'm new to full stacking and have a Create React App hitting a single /api/verify endpoint in an Express backend.
In dev, I proxy the backend in my frontend package.json with "proxy": "localhost:8081"
DevOps needs to deploying this to a GCP nginx env and I need to make the proxy path relative so we don't have to hard code the domain in the proxy.
I have create a .env.development and .env.production but I'm not sure how to use them correctly so a local yarn start proxies localhost:8081 and a production build proxies the real domain.
I have a typical, simple Express server.js but not sure how to tie it all together.
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
var corsOptions = {
origin: 'http://localhost:8081',
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.json());
app.disable('x-powered-by');
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to bezkoder application.' });
});
require('./routes/gallery.routes')(app);
const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
And my single route:
const { authJwt } = require('../middleware');
const galleryController = require('../controllers/gallery.controller.js');
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
'Access-Control-Allow-Headers',
'x-access-token, Origin, Content-Type, Accept',
);
next();
});
app.get(
'/api/verify',
[authJwt.verifyToken],
galleryController.fanPassGallery,
);
};
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
}))
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}`)
});
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