Reputation: 35
I have recently started learning MERN stack and I made my first front-end application using React and I connected it using an API that I have created using Express. It works perfectly fine on my local machine using localhost.
But whenever I try to upload it to a hosting service, like Heroku for example, it gives me a 404 error whenever I open the link. Is there is a way for me to upload my API into a hosting service for free or is there is something I'm doing wrong in my code ?
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
require('dotenv').config({ path: __dirname + '/.env' });
const URI = process.env.URI;
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: true });
const connection = mongoose.connection;
connection.once('once', () => {
console.log('connection to database has been initiated sucessfully');
});
const itemRouter = require('./routes/itemsRouter.js');
const orderRouter = require('./routes/orderRouter.js');
const mailRouter = require('./routes/mailRouter.js');
app.use(express.json());
app.use(cors());
app.use('/items', itemRouter);
app.use('/orders', orderRouter);
app.use('/sendMail', mailRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`App is running on port ${PORT}`);
});
Upvotes: 0
Views: 433
Reputation: 39
Heroku should work out the box if you've followed the setup here Heroku Dev Center.
However, if you're using freshly shipped ubuntu or similar server. You'll need to set up the environment by doing the following:
sudo apt install nodejs nginx
npm install -g pm2
server {
listen 80;
index index.html;
server_name YOUR_DOMAIN/SERVER_IP;
location / {
proxy_pass 127.0.0.1:NODE_BOUND_PORT;
}
}
pm2 start index.js
You'll have to restart nginx and create the symbolic links for NGINX to pick up the routing but once this is done, should route as intended.
Upvotes: 1