I am currently creating an angular web app, that communicates with a node.js backend with express. When I make a GET or POST request to the backend, i get this error message:
Access to XMLHttpRequest at 'http://localhost:9999' from origin 'http://localhost:4200' 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.
After a quick research I added app.use(cors())
to my index.ts file, but It doesn't seem to work. This is my index.ts file:
import { IoContainer } from './core/ioc/ioc.container';
import { LoggerService } from './core/services/logger.service';
import * as express from 'express';
import 'reflect-metadata';
import { InversifyExpressServer } from 'inversify-express-utils';
import { DatabaseService } from './core/services/database.service';
import { appendFile } from 'fs';
const cors = require('cors');
const container = new IoContainer();
container.init();
const logger = container.getContainer().resolve(LoggerService);
const databaseService = container.getContainer().resolve(DatabaseService);
const server = new InversifyExpressServer(container.getContainer());
databaseService.initialize().then(() =>{
const app = server.build();
app.use(cors());
app.listen(9999);
logger.info("Server listening on port 9999");
}).catch(() =>{
logger.error("Error while starting express server");
})
Is there any other solution to this problem?
CodePudding user response:
add below line after app.use(cors());
may fix the problem
app.options('*', cors());
also you can put specific ip address instead *.
CodePudding user response:
I have found a solution to my problem now. I had to add the code inside of the server.setConfig() function like this:
server.setConfig((app) => {
var cors = require('cors');
app.use(cors({origin: `*`}));
app.options('https://localhost:4200', cors());
});