6

Vue CLI 2.x本地开启https运行并代理后端https接口

 2 years ago
source link: https://segmentfault.com/a/1190000041005989
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1.本地生成证书

# 进入项目并在build下新建cert目录
cd ./your-projuct/build && mkdir cert

# 进入cert目录
cd cert

# 使用openssl生成私钥
openssl genrsa -out private.key 1024

# 使用上面生成的私钥生成证书 其中的Common Name输入后端接口的host
openssl req -new -key private.key -out csr.key

# 生成证书签名文件
openssl x509 -req -days 3650 -in csr.key -signkey private.key -out file.crt

2AEF2C7C-0AF4-4443-B4EE-FD8E05D33980.png
(在第四步生成的私钥生成证书时,其中的Common Name配置输入后端接口的host)

2.修改本地启动项目的配置文件

app.js 或者 ./build/dev-server.js,这里截取部分改动代码

const opn = require('opn');
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const proxyMiddleware = require('http-proxy-middleware’);
const webpackConfig = require('./webpack.dev.conf');

const app = express();
const compiler = webpack(webpackConfig);
.
.
.
// 新增部分
const fs = require('fs');
const https = require('https’);

const privateKey = fs.readFileSync(path.join(__dirname, './cert/private.key'),'utf8');
const certificate = fs.readFileSync(path.join(__dirname, './cert/file.crt'),'utf8');
const credentials = { key: privateKey, cert: certificate };
const server = https.createServer(credentials, app);

server.listen(port);

3.重启项目

3.1 问题:Chrome浏览器无法处理杂乱凭据,无法访问https localhost url

00DDDE7A-5944-4C56-B6F1-1D6BBEE928A9.png

解决:点击页面任意处,直接使用键盘输入 thisisunsafe 后回车即可正常访问

3.2 问题:无法访问后端接口,报错DEPTH_ZERO_SELF_SIGNED_CERT

2C241441-9C69-4B38-ABB9-CB3F5987E57F.png

解决:需要在proxyTable的每个对象中增加secure:false

// 每个对象中增加secure:false
const proxyHost = 'https://www.your-domain.com';
const proxyTable = {
    '/YOURKEYWORD': {
    target: proxyHost,
    changeOrigin: true,
    secure: false
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK