DEV Community

Victor Maina
Victor Maina

Posted on

Resolving CORS Issues

CORS (Cross-Origin Resource Sharing) errors occur when the frontend and backend are hosted on different domains or ports. To fix this:

Install CORS Middleware:
In your backend, install the cors package:

bash
Copy
npm install cors
Enable CORS:
Update your backend code to allow requests from the frontend:

javascript
Copy
const cors = require('cors');
const express = require('express');
const app = express();

app.use(cors({
origin: 'http://102.37.21.212:3000', // Frontend URL
credentials: true
}));

app.post('/auth/login', (req, res) => {
// Handle login
});

app.listen(4000, () => {
console.log('Backend running on port 4000');
});
Restart the Backend:
Restart the backend to apply the changes:

bash
Copy
pm2 restart uvotake-backend
This ensures the backend accepts requests from the frontend.

  1. Opening Ports in Azure To allow external access to your app, open the necessary ports in Azure:

Go to your VM in the Azure Portal.

Under Networking, add inbound port rules:

Frontend: Open port 3000 for HTTP access.

Backend: Open port 4000 for API access.

Save the rules and test connectivity:

bash
Copy
curl http://:3000
curl http://:4000/auth/login
This ensures your app is accessible to users.

  1. Using PM2 for Process Management To keep your app running after disconnecting from the VM, use PM2:

Install PM2:

bash
Copy
sudo npm install -g pm2
Start the App:
Use PM2 to serve the frontend:

bash
Copy
pm2 serve build 3000 --name "uvotake-frontend"
Save the Process:
Ensure the app starts automatically after a reboot:

bash
Copy
pm2 save
pm2 startup
PM2 ensures your app runs continuously.

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay