因为想做语音功能,找到navigator.mediaDevices.getUserMedia方法需要在https协议下才可以调用,于是第一步是解决vue-cli搭建的项目如何支持https访问。
首先感谢几篇文章:
-
https://github.com/zp1112/blog/issues/4
是针对vue-cli项目如何加入本地https,但是vue-cli是老版的,使用的还是dev-server.js。 -
http://blog.fens.me/nodejs-https-server/
讲的是用Nodejs创建HTTPS服务器,关键是openssl生成证书文件,如果本地没有证书,要先生成证书。 -
https://blog.csdn.net/kitok/article/details/72957185
关于如何安装openssl。可以通过openssl version -a指令确认下本机是否已安装openssl,没有的话就直接下载对应环境的exe安装包安装一下。 -
https://webpack.docschina.org/configuration/dev-server/#devserver-https
关于webpack的devServer配置
要处理的是build文件夹如下
build目录.png
- 增加cert文件夹,其中包括要用的openssl证书;
- 修改webpack.dev.conf.js。新版vue-cli已经改用webpack的devServer来代替之前的dev-server。
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
/*---------添加以下2句,引入https和fs---------*/
const https = require('https')
const fs = require('fs')
/*---------添加以上2句,引入https和fs---------*/
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
devtool: config.dev.devtool,
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false,
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true,
watchOptions: {
poll: config.dev.poll,
},
disableHostCheck: true,
/*---------添加https配置---------*/
https: {
key: fs.readFileSync(path.join(__dirname, './cert/privatekey.pem')),
cert: fs.readFileSync(path.join(__dirname, './cert/certificate.pem'))
}
/*---------添加https配置---------*/
},
............................
以下代码省略
以上,解决!
网友评论