如何在nodeJs https服务器中启用cors

时间:2019-02-07 11:24:09

标签: node.js angular express https cors

我已经使用OpenSSL生成了虚拟SSL证书,并将其导入到nodejs服务器中。并使用https启动服务器。前端是angular 6(使用let-encrypt && nginx配置HTTPS)应用程序,但它在不同的AWS实例上运行,而节点服务器在不同的实例上。我也处理了CORS,但是无论何时从https angular到后端HTTPS服务器的调用都没有响应。但是当我尝试使用HTTP时,一切都很好。

。`

   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');
        });

0 个答案:

没有答案