1.生成证书文件
//生成私钥key文件:
openssl genrsa 1024 > /文件路径/private.pem
//通过私钥文件生成CSR证书签名:
openssl req -new -key /文件路径/private.pem -out /文件路径/csr.pem
//通过私钥文件和CSR证书签名生成证书文件:
openssl x509 -req -days 365 -in /文件路径/csr.pem -signkey /文件路径/private.pem -out /文件路径/file.crt
2.导入fs文件操作模块
npm install fs --save
3.修改启动文件./bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('chat-s:server');
var http = require('http');
var https = require('https');
var fs = require('fs');
/**
* 设置https证书和私钥key
*/
var options = {
key: fs.readFileSync('/文件路径/private.pem'),
cert: fs.readFileSync('/文件路径/file.crt')
};
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
/**
* Create HTTP server.
*/
//注释http服务的创建,修改为https服务
// var server = http.createServer(app);
var server = https.createServer(options,app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
4.node.js服务启动
npm start
结果
因为是自己生成的证书,未经过安全验证,正式环境需要去申请