yaogengzhu / daily-share

个人博客记录、内容在issues
30 stars 4 forks source link

本地如何配置https环境(2021-09-07) #138

Open yaogengzhu opened 3 years ago

yaogengzhu commented 3 years ago

本地环境如何配置https

当我们需要对高德地图本地联调时,发现需要的是https环境。这时无法调用定位接口~此时需要给本地环境配置一个https环境

准备工作

需要解决以下两个问题:

  1. 配置https环境,首先需要配置https相关证书,那么如何获取证书呢?
  2. 证书配置完成后,如何配置到开发环境中

如何获取https证书

证书一般有两个

这里我们使用 mkcert 来生成证书,对于mkcert 可以点击这里了解

brew install mkcert // 对于mac环境我们可以使用brew安装

开始生成相关证书。----- 以域名framework.bnq.com.cn举例子

mkcert 'framework.bnq.com.cn' Using the local CA at 'framework.bnq.com.cn' // 例如你的域名framework.bnq.com.cn

执行该脚本后,会在该目录下生成两个文件

framework.bnq.com.cn+6-key.pem // 文件1
framework.bnq.com.cn+6.pem // 文件2

如何配置开发环境

首先你需要配置hosts

127.0.0.1       framework.bnq.com.cn // 配置hosts你的开发环境的域名

用express环境作为例子. 把生成的两个文件移动到指定的文件夹上,这里放置mkcert目录下

const https = require('https');
const http = require('http');
const fs = require('fs');
const express = require('express');
const app = express();

// 关键步骤
const options = {
    key: fs.readFileSync(path.resolve(__dirname, './mkcert/framework.bnq.com.cn+6-key.pem')),
    cert: fs.readFileSync(path.resolve(__dirname, './mkcert/framework.bnq.com.cn+6.pem')),
};
const httpsServer = https.createServer(options, app);
const httpServer = http.createServer(app);

/**
    .
    . 省略n行其他代码
    .
*/
httpServer.listen(port, (err) => {
    console.log(config[ENV]['apiUrl']); // 你的环境地址
    if (err) {
        console.log(err);
        return;
    }

    if (autoOpenBrowser && process.env.CURRENT_ENV !== 'production') {
        open(config[ENV]['apiUrl']);
    }
});

// 启用https服务 启用443
httpsServer.listen(443, (err) => {
    console.log(config[ENV]['apiUrl']);

    if (err) {
        console.log(err);
        return;
    }

    if (autoOpenBrowser && process.env.CURRENT_ENV !== 'production') {
        open(config[ENV]['apiUrl']);
    }
});

完成以上步骤基本完成了

此时已经完成了https环境

webpack配置(补充)

{
  ...
  devServer: {
    https: true,
    key: fs.readFileSync(path.resolve(__dirname, './mkcert/framework.bnq.com.cn+6-key.pem')),
    cert: fs.readFileSync(path.resolve(__dirname, './mkcert/framework.bnq.com.cn+6.pem')),
  }
  ...
}
taosiqi commented 3 years ago

localhost也可以定位吧

yaogengzhu commented 3 years ago

localhost也可以定位吧

必须https协议才行了!