当前位置: 首页 > 后端技术 > Node.js

VueCLI2.x启用https本地运行并代理后端https接口

时间:2023-04-03 16:10:03 Node.js

1.本地生成证书#进入项目,在build下新建cert目录cd./your-projuct/build&&mkdircert#进入cert目录cdcert#使用openssl生成私钥opensslgenrsa-outprivate.key1024#使用上面生成的输入私钥的通用名为后端接口生成证书hostopensslreq-new-keyprivate.key-outcsr.key#生成证书签名文件opensslx509-req-days3650-在csr.key-signkeyprivate.key-outfile.crt(第四步生成的私钥生成证书时,里面的CommonName配置进入后端接口的host)2.修改配置文件app.本地启动项目的.js或./build/dev-server.js,这里截取部分改动的代码constopn=require('opn');constpath=require('path');constexpress=require('表达');constwebpack=require('webpack');constproxyMiddleware=require('http-proxy-middleware');constwebpackConfig=require('./webpack.dev.conf');constapp=express();constcompiler=webpack(webpackConfig);...//新部分constfs=require('fs');consthttps=require('https');constprivateKey=fs.readFileSync(path.join(__dirname,'./cert/private.key'),'utf8');constcertificate=fs.readFileSync(path.join(__dirname,'./cert/file.crt'),'utf8');坚守信念ntials={key:privateKey,cert:证书};constserver=https.createServer(credentials,app);server.listen(port);3、重启项目3.1问题:Chrome无法处理杂乱的凭据,无法访问httpslocalhostURL解决方法:点击页面任意位置,直接使用键盘输入thisisunsafe回车即可正常访问3.2问题:无法访问后台接口,报错DEPTH_ZERO_SELF_SIGNED_CERT解决方法:需要在proxyTable中的每个对象添加secure:false//每个对象添加secure:falseconstproxyHost='https://www.your-domain.com';constproxyTable={'/YOURKEYWORD':{target:proxyHost,changeOrigin:true,secure:false}