jaber
jaber

Reputation: 35

Is there is a way for me to host my express api on the internet?

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

Answers (1)

Rhys Sharratt
Rhys Sharratt

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:

  • Install node run time, nginx & a node deamon manager (In this case PM2)
    • sudo apt install nodejs nginx
    • npm install -g pm2
  • Create an nginx config
    server {
      listen 80;
      index index.html;
      server_name YOUR_DOMAIN/SERVER_IP;
    
      location / {
        proxy_pass 127.0.0.1:NODE_BOUND_PORT;
      }
    }
    
  • Deamonise the Node script
    • 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

Related Questions