Hey everyone! I’m working on a project hosted on an AWS Windows EC2 instance. Right now my website is served on port 80 and the API runs on port 5000. I want to simplify things by having both the frontend and backend accessible through the same port.
Currently it looks like this:
What I’m aiming for:
Is there a way to set this up without making users type in a port number for API calls? I’m not sure how to create a single server file that handles both the website and API routes. Any tips or examples would be super helpful!
Here’s a basic idea of what I’m thinking:
const express = require('express')
const app = express()
// Serve static files for the website
app.use(express.static('public'))
// API routes
app.get('/api/users', (req, res) => {
res.json([{name: 'Alice'}, {name: 'Bob'}])
})
app.listen(80, () => console.log('Server running'))
Is this on the right track? Thanks in advance for any advice!
yo, ur express.js approach looks solid! u could add more api routes like ‘/api/products’ and use a catch-all route for ur frontend. like this:
app.get(‘*’, (req, res) => {
res.sendFile(__dirname + ‘/public/index.html’);
});
this way, everything works thru port 80. no need for users to mess with port numbers. neat, right?
hey there! have u considered using a reverse proxy like nginx? it’s a neat way to route both ur website and api through port 80. u could keep ur current setup but let nginx handle the routing. it’s pretty flexible and can scale well. what do u think about that approach? any concerns about setting it up?
Your approach with Express.js is solid and can effectively combine your web app and API on a single port. To enhance this setup, consider implementing middleware for API routes to handle common tasks like authentication or logging. For example:
const apiMiddleware = (req, res, next) => {
// Add API-specific logic here
console.log(‘API request:’, req.path);
next();
};
app.use(‘/api’, apiMiddleware);
This way, you can apply consistent handling across all API routes. Additionally, consider error handling for both your web app and API:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(‘Something went wrong!’);
});
This setup provides a robust foundation for serving both your website and API through a single port, improving user experience and simplifying your infrastructure.