1

I made a simple full stack app for a job application using a mern stack. The application requires the app to be deployed on replit. I was able to run my app from my laptop but I am having issue connecting my back end with my front end api calls.

I have not used replit or other online coding platforms much before, so I am not very sure how to. If I run my front end on replit and my back end from my local laptop files, the api calls are working fine. But If I run start both front and back end on replit, the server will start but no API calls will reach it.

Here is the replit link: https://replit.com/@MayurKumar4/In-replit-how-to-connect-to-mongoosemongo-api-endpoints?v=1

Below is the index page of my express app.

The dbURI is currently linked to a mongodb atlas cluster I have set up and is working with some seed data.

port is set to 4000

import express from 'express'
import mongoose from 'mongoose'
import router from './config/routes.js'
import { port, dbURI } from './config/environment.js'
import cors from 'cors'

const app = express()

const startServer = async () => {
try {
// Attempt mongodb connection
await mongoose.connect(dbURI)
console.log('Mongodb connected')

// --Middleware--
// JSON Parser
app.use(express.json())


app.use(cors())


// Logger
app.use((req, _res, next) => {
  console.log(` Request received: ${req.method} - ${req.url}`)
  next()
})

// Routes
app.use('/api', router)

// Catch All
app.use((_req, res) => {
  return res.status(404).json({ message: 'Route Not Found' })
})

// If mongodb connects successfully
app.listen(port, () => console.log(` Server listening on port ${port}`))
} catch (err) {
console.log(err)
  }
 }
 startServer()
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Mayur Kumar
  • 67
  • 1
  • 5
  • In order to deploy a MERN app to a node environment you need to 1. build the React frontend (`npm run build`) and copy the result inside your express public folder. 2. [setup express for static files](https://expressjs.com/en/starter/static-files.html) 3. make sure your React app makes API calls to its own server (i.e. URLs start with `/api` and not `http://localhost`). To make this work during development, use the `proxy` field of your package.json to state your dev backend host and port –  Jun 01 '22 at 20:52

0 Answers0