i have two Angular SSR projects with nodeJS backend, where my cors setup was working fine. Now iam doing a third project, with the exact same setup and i get now an error message, which i can not understand:
Access to fetch at ‘https://backend.my-domain.de/login’ from origin ‘https://my-domain.de’ 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 requests do contain a ‘Access-Control-Allow-Origin’:’https://my-domain.de’, as well as my backend cors config: cors({origin: ‘https://my-domain.de’}). Since i did that successfully the two projects before, i cannot understand, why this is suddenly happening. I really hope, someone can give my a hint to that problem. Even more strange is, that this error message only gets raised by chrome, no other browser. But its not working in all browsers.
Please see my code below:
Angular Registration Service for example:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class RegistrationService {
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'https://my-domain.de',
})
};
userRegistration(body : FormData) {
return this.http.post(environment.registration, body, this.httpOptions);
}
}
As you can see iam parsing the httpOptions object to the request and that did work in the past.
Here is my nodeJS:
const APIconfig = require(`${__dirname}/config/config.loader.js`);
const httpRoutesConfiguration = require(`${__dirname}/config/http.routes.configuration.js`);
const CorsConfiguration = require(`${__dirname}/config/cors.config.js`)
const { logger } = require(`${__dirname}/config/logger.js`)
const express = require('express');
const server = require('http');
const WebsocketServerConfiguration = require(`${__dirname}/websocket.server.js`);
const { fromEvent } = require('rxjs');
const { tap } = require('rxjs/operators');
const mongoose = require('mongoose');
(async () => {
try {
const app = express();
const API = await new APIconfig(`${__dirname}/config/APIconfig.json`).getConfig();
mongoose.connect(API.MONGODB_PRODENVIROMENT_API);
const serverInstance = server.createServer(app);
fromEvent(serverInstance.listen(API.PORT, () => console.log(`Server is listening on 'http://localhost:${API.PORT}`)), 'listening')
.pipe(
tap(new CorsConfiguration(app)),
tap(new httpRoutesConfiguration(app)),
tap(new WebsocketServerConfiguration(serverInstance)),
)
} catch (ex) {
logger.error(ex);
}
})();
The RxJS Tap operator applies the Cors Config on the app object.
And the cors configuration. Even if i change the origin temporary to origin: “*” doesnt help. Comment out the WebsocketServer doesnt help eather:
const cors = require('cors');
module.exports = class CorsConfiguration {
constructor(app) {
app.use(
cors({
origin: 'https://my-app.de' // "*" did not do the job eather
})
)
}
}
The http route configuration looks as follows:
const playerController = require(`${__dirname}/../controller/player.controller.js`);
const multer = require('multer');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
module.exports = class HttpRoutesConfiguration {
constructor(app) {
const storage = multer.diskStorage({
destination: (reg, file, cb) => {
cb(null, 'img')
},
filename: (reg, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({ storage: storage });
app.use("/img", express.static('img')); //serve static img files
app.post('/registerNewPlayer', upload.single("avatarPicture"), playerController.registerNewPlayer);
app.post('/login', bodyParser.json(), playerController.loginUser);
app.post('/addPlayer', upload.single("avatarPicture"), playerController.addPlayer);
app.post('/deleteUser', bodyParser.json(), playerController.deleteUser);
}
}
iam running both frontend and backend on one single machine with traeffik proxy with the following configuration:
version: '3'
services:
backend:
image: node:latest
command: node /usr/src/app/index.js
volumes:
- ./dist:/usr/src/app
networks:
- default
- web
labels:
- traefik.enable=true
- traefik.http.routers.backend.rule=Host(`backend.my-domain.de`) && PathPrefix(`/{path:.*}`)
- traefik.http.routers.backend.tls=true
- traefik.http.routers.backend.tls.certresolver=lets-encrypt
- traefik.http.services.backend.loadbalancer.server.port=8080
networks:
web:
external: true
to clearify: Frontend runs on port 5000 with the origin “https://my-domain.de”. I also registered a subdomain https://backend.my-domain.de, which i use for the backend API calls and a corresponding rule for traeffik proxy.
Again, all of this configuration worked in the past without any single problem. I would be really thankful if you can help me. Let me know, if you need any further information. Regards, Marc