Hey guys, I’m working on a project using an AWS Windows EC2 instance. Right now, my frontend is on port 80 and the backend is on port 5000. I’m wondering if there’s a way to put both on the same port without needing a separate port for the API calls.
Currently, it looks like this:
- Frontend:
mysite.com
- Backend:
mysite.com:5000
But I’d like it to be something like:
Does anyone know how to set this up? I’m thinking maybe I need to write a single server file that handles both frontend and backend routing, but I’m not sure where to start. Any tips or examples would be super helpful!
// Example server setup (not working, need help!)
const express = require('express')
const app = express()
// Frontend routes
app.get('/', (req, res) => {
res.send('Welcome to my site!')
})
// Backend routes
app.get('/api/data', (req, res) => {
res.json({ message: 'This is from the backend' })
})
app.listen(80, () => console.log('Server running'))
Thanks in advance for any help!
yo, i’ve done this before! u can use express middleware to handle both. serve ur static files with express.static for the frontend, then use app.use(‘/api’, apiRouter) for backend routes. keeps everything on one port. easy peasy! lemme know if u need more help setting it up
I’ve encountered a similar situation in one of my projects. Instead of using a reverse proxy, I opted for a more integrated approach using Express.js as both the frontend and backend server. Here’s how you can achieve this:
Create a single Express server that serves your frontend static files and also handles your API routes. Use the express.static middleware to serve your frontend files from a ‘public’ directory. Then, define your API routes with a ‘/api’ prefix.
This way, all requests to ‘mysite.com’ will serve your frontend, while requests to ‘mysite.com/api’ will be handled by your backend logic. It’s a clean solution that doesn’t require additional server configuration.
Remember to adjust your frontend API calls to use relative paths (‘/api/…’) instead of absolute URLs. This approach has worked well for me in production environments, simplifying deployment and reducing potential points of failure.
hey there! have you considered using a reverse proxy like nginx? it can route requests to different ports based on the url path. so ‘/api’ could go to your backend on 5000, while everything else goes to the frontend on 80. it’s pretty neat! what backend framework are you using? that might affect the setup a bit. curious to hear more about your project!