如何使用express.js创建HTTPS服务器

时间:2018-12-15 06:43:39

标签: javascript node.js angular express

下面的代码是我的expressJs服务器。我也为前端启用了HTTPS和cors。 (在Angular 6中将字体End和导入的SSL证书使用Angular 6)。但是每当我从前端请求服务器或使用邮递员时。我没有收到任何错误,也没有回应。但是如果我检查服务器端日志是否正在打印特别要求的API。但是,如果我直接在Google chrome中调用该API URL并禁用安全警告,那么它将在该页面中打印该响应。

require('./config/config');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var path = require('path');
require('./models/call-logs_model');
var morgan = require('morgan');
var app = express();

const port = process.env.PORT;

var originsWhitelist = [
  'http://192.168.0.174:8080',   
  'http://192.168.0.163:8080',
  'http://192.168.0.189:8080'
];
var corsOptions = {
  origin: function(origin, callback){
        var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
        callback(null, isWhitelisted);
  },
  credentials:true
}
app.use(cors(corsOptions));
app.use(morgan('tiny'));
app.use(fileUpload());
app.use(bodyParser.json());
app.use(require('./routes'));

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

app.use((error, req, res, next) => {
  res.status(error.status || 500)
  res.json({
    error: error.message
  })
});


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

module.exports = {app};

0 个答案:

没有答案