jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

node配合express 给网站添加https #45

Open jackieli123723 opened 6 years ago

jackieli123723 commented 6 years ago

打包的http cdn资源改为https 接口api也要换为https

//index.html

 <link href="https://cdn.bootcss.com/highlight.js/8.0/styles/monokai_sublime.min.css" rel="stylesheet">  
    <script src="https://cdn.bootcss.com/highlight.js/8.0/highlight.min.js"></script>

//src/api/index.js

//dev https
const serverRoot = process.env.NODE_ENV === 'development' ? "https://192.168.10.85:3008/" : "https://192.168.10.85:3008/";
export default serverRoot;

var express = require('express'),
    https = require('https'),
    path = require('path'),
    helmet = require('helmet'),
    compression = require('compression'),
    fs = require('fs'),
    PORT = process.env.PORT || 8443,
    HOST = process.env.HOST || '';

var app = express();

app.use(helmet());
app.use(compression());
app.use(express.static(path.join(__dirname, '/dist')));

app.get('*', (req, res) => {
  res.send(fs.readFileSync(path.join(__dirname, '/dist/index.html'), 'utf8'));
})

var options = {
    key  : fs.readFileSync('./key.pem'),
    ca   : fs.readFileSync('./csr.pem'),
    cert : fs.readFileSync('./cert.pem')
}

https.createServer(options, app).listen(PORT, HOST, null, function() {
    console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
    console.log(`代码部署成功访问端口https://localhost:${this.address().port}`);
});

Create the private key :

openssl genrsa -out key.pem 1024

Create the "Certificate Signing Request" :

openssl req -new -key key.pem -out csr.pem

Create the self-signed certificate :

openssl x509 -req -in csr.pem -signkey key.pem -out cert.pem