Linked Questions

Popular Questions

How to enable cors in nodeJs https server

Asked by At

I have generated dummy SSL certificate using OpenSSL and import that in nodejs server. and started the server with https. And front end is angular 6 (config HTTPS with lets-encrypt && nginx ) app but it is running on different aws instance and node server is on a different instance. I handled CORS also but whenever a call from https angular to the backend HTTPS server is not responding anything. but when I try with HTTP everything is working fine.

.`

   var originsWhitelist = [
      'http://XXX.XX.XX.XXX.:8080',
      'https://test.XXXXX.in/'
   ];
   var corsOptions = {
       origin: function(origin, callback){
           var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
           callback(null, isWhitelisted);
       },
       credentials:true
    }
    app.use(cors(corsOptions)); 

    app.use((req,res,next) => {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
       if (req.method === 'OPTIONS') {
         res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
         return res.status(200).json({});
       }
       const error = new Error('Not found');
       error.status = 200;
       next(error); 
    });

       var options = {
          key: fs.readFileSync(path.join(__dirname,'privateKey','client-key.pem')),
          cert: fs.readFileSync(path.join(__dirname,'privateKey','client-cert.pem'))
        };
        http.createServer(app).listen(3000 , ()=>{
          console.log('Started up HTTP at port 3000');
        });

        https.createServer(options, app ).listen(3001, ()=>{
          console.log('Started up HTTPS at port 3001');
        });

Related Questions