node服务器支持https请求
2021/11/25 17:10:53
本文主要是介绍node服务器支持https请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
node服务器支持https请求
水文一篇
问题
前段时间给自己的域名接入了https,但是前端向后端发起请求的时候报了这么一个错误
net::ERR_SSL_PROTOCOL_ERROR
意思是https的请求不能向http服务器发起,所以,我们要把node服务加上ssl
操作
const express = require("express"); const app = express(); const https = require('https'); const fs = require('fs'); // node接入证书 const privateKey = fs.readFileSync('./ssl/privkey.pem', 'utf8'); const certificate = fs.readFileSync('./ssl/cert.pem', 'utf8'); const ca = fs.readFileSync('./ssl/chain.pem', 'utf8'); const credentials = { key: privateKey, cert: certificate, ca: ca }; // 跨域 app.use(require("cors")()); //处理post请求,解析json数据 (中间件) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // jsonwebtoken生成token app.set("secret", "vuereactnodeblog"); // 引入mongoose require("./mongodb/db")(app); // 引入路由 import router from "./routes/index.js"; router(app); // 引入微医图书超时扣分器(每天23:59:50秒检测是否逾期,如果逾期设置逾期状态并且) require("./utils/outtime")(); const httpsServer = https.createServer(credentials, app); // http监听3000端口 httpsServer.listen(3000, () => { console.log("App Listening on port 3000"); });
const privateKey = fs.readFileSync('./ssl/privkey.pem', 'utf8'); const certificate = fs.readFileSync('./ssl/cert.pem', 'utf8'); const ca = fs.readFileSync('./ssl/chain.pem', 'utf8');
这三个文件的地址在我配置的 letsencypt 文件夹里面,看文章配置的兄弟们注意如果配置的ssl不是用 letsencypt 或者 用的阿里云或腾讯云的免费ssl证书,不要参考我这个方法配置!(应该是用key与pem双文件配置)
配置完了,我们就可以登录进去了
但是右上方显示了不安全,这是我的域名直接请求了 https://47.95.234.230:3000导致的,虽说https请求http的问题(禁止混合)解决了,但是这个证书只针对与域名 codeting.top有效,所以,请求 https://47.95.234.230:3000是不安全的。
这个时候我们只需要将 47.95.234.230:3000(3000这个端口或者这个服务映射到域名上就可以了),大家可以通过nginx配置,我这儿比较懒,直接宝塔面板映射,方便。
改完了,修改前端的请求IP为域名,就可以了。
这篇关于node服务器支持https请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?