ssl证书-https重定向
ssl证书-https重定向
一. 重定向问题
1.1 为什么要重定向
- 因为
http不安全要转成https的地址 https- 申请
SSL证书 并安装
- 申请
const https = require('https')
const options = {
cert: fs.readFileSync('........pem'),
key: fs.readFileSync('........key')
}
https.createServer(options, app).listen(8103)
1.2 重定向实现部分
- 将不是
https的端口改为https的端口
app.get('*', function (req, res) {
if (req.protocol !== 'https') {
let host = req.headers.host;
console.log(req.headers.host)
const reg = /(?<=(\:))\d+/
const result = host.match(reg)[0]
host = host.replace(reg, '8103')
console.log(`https://${host}${req.path}`)
res.redirect(302, `https://${host}${req.path}`)
// res.location(`https://${host}${req.path}`)
}
})
- 为什么要有
http的端口和https的端口?
1.3 发现的问题
- 若是这样配置了静态资源
app.use(express.static('./dist/'))- 发现重定向是没有效果的
- 配置成这样
app.use('/dist', express.static('./dist/'))却发现无法解析文件
// 我的解析文件是这样的
app.get('/', (req, res) => {
fs.readFile('./dist/index.html', (err, data) => {
if (err) {
return res.end('404 Not Found')
}
const htmlStr = data.toString()
res.end(htmlStr)
})
})
- 不知道是不是由于我部署的是
vue是单页面富应用的问题
1.4 解决方法
-
在第一个重定向记得加next()
- 解决了浏览器的URL没有跳转的问题
-
然而还是有问题: 所有path路径都访问同一个
index.html- 解决方法: 加入
path的判断再用fs导入文件
- 解决方法: 加入
-
再出现新问题: 显示空白页并报错

-
发现是一些
css文件不能解析出来
1.5 终极解决方法
- 重新设置成
app.set('views', path.join(__dirname, './')) - 然后把上面那段代码放在重定向的代码下面!
- 结果…发现如果用
https的网站, 其接口也要使用https的接口… - 卒…
1.6 新新新问题–把接口换成https
- 因为用是不同
ip的接口, 所以报错证书文件不合法net::ERR_CERT_COMMON_NAME_INVALID- 然而本地部署的
npm run serve却可以访问这个接口
- 解决方法
const https = require('https')
// 用instance来代替axios并加入https模块对应的rejectUnauthorized: false
const instance = axios.create({
baseURL: '...',
timeout: 1000,
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
})
-
问题终于可以正常访问了
- 但是~

- 但是~
-
所以还是要购买一个域名申请对应的证书

浙公网安备 33010602011771号