We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Node.js用于做小程序后台服务,域名要求必须是Https协议。在Node.js开启Http服务是非常简单的,如下:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' }); res.end('访问成功') }); server.listen(8080, () => { console.log('服务已开启'); })
如果想使用Https服务需要两步:1. 需要有一份SSL证书;2. 使用Node.js自身的Https模块。
获取SSL证书方式有两种:
我是使用某云平台提供免费的证书
点击下载后选择服务器类型
下载后的文件分别是以.key、.pem为后缀,其中.key文件是base64加密私钥,.pem文件是base64加密的证书
.key、.pem
.key
.pem
相较Http,它多了一个options参数。
const https = require('https'); const fs = require('fs'); const path = require('path'); const options = { key: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.key')), cert: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.pem')), }; const server = https.createServer(options, (req, res) => { res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' }); res.end('访问成功') }); server.listen(8080, () => { console.log('服务已开启'); })
由于SSL证书我绑定的域名是www.linglan01.cn ,当我使用https://127.0.0.1:8080 访问服务时与绑定的域名不相符,它会被拦截访问,仅允许 www.linglan01.cn 访问。
使用域名为www.linglan01.cn 才能正常的访问。
工作中肯定是使用社区的Express等框架进行开发,想在Express等框架中开启Https也非常容易,以Express举例:
const https = require('https'); const fs = require('fs'); const path = require('path'); const express = require('express') const app = express(); app.get('/chat', (req, res) => { res.send('我是https') }); const options = { key: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.key')), cert: fs.readFileSync(path.join(__dirname, './ssl/9499016_www.linglan01.cn.pem')), }; const server = https.createServer(options, app); server.listen(8080, () => { console.log('服务已开启'); })
Node.js中搭建Https服务不难,Node.js已经为我们提供了Https模块可以快捷的完成搭建。Https服务实际中仅会使用到线上环境,如果本地环境也需要,我们也可以使用openSSL工具生成一个证书。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Node.js用于做小程序后台服务,域名要求必须是Https协议。在Node.js开启Http服务是非常简单的,如下:
如果想使用Https服务需要两步:1. 需要有一份SSL证书;2. 使用Node.js自身的Https模块。
SSL证书
获取SSL证书方式有两种:
我是使用某云平台提供免费的证书
点击下载后选择服务器类型
下载后的文件分别是以
.key、.pem
为后缀,其中.key
文件是base64加密私钥,.pem
文件是base64加密的证书使用Node.js自身的Https模块开启一个服务
相较Http,它多了一个options参数。
由于SSL证书我绑定的域名是www.linglan01.cn ,当我使用https://127.0.0.1:8080 访问服务时与绑定的域名不相符,它会被拦截访问,仅允许 www.linglan01.cn 访问。
使用域名为www.linglan01.cn 才能正常的访问。
使用Express框架开启Https
工作中肯定是使用社区的Express等框架进行开发,想在Express等框架中开启Https也非常容易,以Express举例:
总结
Node.js中搭建Https服务不难,Node.js已经为我们提供了Https模块可以快捷的完成搭建。Https服务实际中仅会使用到线上环境,如果本地环境也需要,我们也可以使用openSSL工具生成一个证书。
The text was updated successfully, but these errors were encountered: