-1

I have a question about CORS in NodeJS. This is my API code working on sub domain api.mydomainname.com.pl and it communicates with my web app created in Angular on domain mydomainname.com.pl.

import express from 'express';
import bodyParser from 'body-parser';
import * as dotenv from 'dotenv';
import morgan from 'morgan';
import swaggerUI from 'swagger-ui-express';
import * as swaggerDoc from './swagger.json';
import * as http from 'http';
import cors from 'cors';

dotenv.config();

import publicRoutes from './routes/public';
import siteRoutes from './utils/site';
import userRoutes from './routes/user';
import refereeRoutes from './routes/referee';
import adminRoutes from './routes/admin';
import emptyRoutes from './routes/empty';
import deviceRoutes from './routes/device';
import { apiRatelimit } from './utils/ddos_protection';
import * as socketIO from './utils/socket';
import * as JWT from './utils/jwt';
import * as auth from './utils/auth';
import * as Nodemailer from './utils/nodemailer'

const hostName = '127.0.0.1';
const app = express();
const httpServer = http.createServer(app);
const corsOptions = {
    origin: ['https://test.robomotion.com.pl', 'https://robomotion.com.pl', 'http://localhost:4200'],
    optionsSuccessStatus: 200,
    methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT'],
    allowedHeaders: ['Content-Type', 'x-requested-with', 'Authorization', 'Accept', 'token'],
    maxAge: 86400
};

const io = socketIO.default.init(httpServer, { cors: corsOptions });
const nodemailer = Nodemailer.default.init();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

const port = Number(process.env.SERVER_PORT) || 8080;

app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(swaggerDoc));

app.use(apiRatelimit); //DDOS prtection

app.use(bodyParser.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }))

app.use(morgan('short'));

app.use(cors(corsOptions));

app.use('/site', siteRoutes);
app.use('/public', publicRoutes);
app.use('/user', JWT.default.verify, auth.default.authorize(0), userRoutes);
app.use('/referee', JWT.default.verify, auth.default.authorize(1), refereeRoutes);
app.use('/admin', JWT.default.verify, auth.default.authorize(2), adminRoutes);
app.use('/device', auth.default.authorize(3), deviceRoutes);

app.use(emptyRoutes); //When can't resolve the path

const server = httpServer.listen(port, hostName, () => {
    console.log(`Server running at http://${hostName}:${port}`);
});

This configuration works well on most of clients but there are small group of users which getting this error: Access to XMLHttpRequest at 'https://mydomainname.com.pl' from origin 'https://api.mydomainname.com.pl' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' (Screenshot). Also if few users (about 10) is using my app simultaneously, this error occurs. Have you any idea why this problem is occuring? Do you think that is problem with client side (in Angular) or on server side (on NodeJS)? Thank you in advance for any help.

Rafael
  • 1
  • Does this answer your question? [How to enable cors nodejs with express?](https://stackoverflow.com/questions/43150051/how-to-enable-cors-nodejs-with-express) – Drenai Nov 26 '21 at 08:28

1 Answers1

-1

The problem is that https://api.mydomainname.com.pl is not in your list of allowed origins.

If you want to enable CORS for this origin as well you need to edit the configuration.

const corsOptions = {
    origin: ['https://test.robomotion.com.pl', 'https://robomotion.com.pl', 'http://localhost:4200', 'https://api.mydomainname.com.pl'],
    optionsSuccessStatus: 200,
    methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT'],
    allowedHeaders: ['Content-Type', 'x-requested-with', 'Authorization', 'Accept', 'token'],
    maxAge: 86400
};
Ayzrian
  • 2,279
  • 1
  • 7
  • 14