CORS issue when frontend tries to send api request to backend

I have a backend running on render. I also have a frontend (static site) running on render. Clicking the frontend link leads to a sign-in page. When I try to sign in, I get this error -
Access to XMLHttpRequest at ‘https://stayfit-backend-xv9v.onrender.com/api/help/login’ from origin ‘https://stayfit-client.onrender.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

My app.ts file looks like this -

import { Server } from "@overnightjs/core";
import { initDB } from "./models";
import { ApiController } from "./controllers/ApiController";
import * as bodyParser from "body-parser";
import session from "express-session";
import cookieParser  from "cookie-parser";
import * as http from 'http';
import cors from 'cors';

export class App extends Server {
	private close: http.Server;

	constructor() {
		super();
		// setting up session
		this.app.use(
			session({
				secret: "secret",
				resave: true,
				saveUninitialized: true,
				cookie: {maxAge: 60 * 1000 * 300},
				rolling: true // reset exipration date with every request
			})
		);
		this.applyMiddleWares();
		this.boostrap();
		this.setupControllers();
	}

	public start(): void {
		const port = 10000;

		this.app.use((req, res, next) => {
			res.header('Access-Control-Allow-Origin', '*');
			res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
			next();
		});

		// Enable CORS for all routes
		this.app.use(cors());

		// Use the cookie-parser middleware
		this.app.use(cookieParser());

		this.close = this.app.listen(port, () => {
            console.log('Server listening on port: ' + port);
        });

	}

	private applyMiddleWares() {
		this.app.use(bodyParser.json());
		this.app.use(bodyParser.urlencoded({ extended: false }));
	}

	private async boostrap() {
		// Connect to db
		await initDB();
	}

	private setupControllers() {
		super.addControllers(new ApiController());
	}
}

Hi @minhaj2OOO,

It looks like your services have been deleted.

Regarding this issue, one thing to consider in the future is avoiding the use of a wildcard character in the header:

Note: When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard. (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)

Please feel free to reach out again if you have any more questions.

Regards,
Mike

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.