Nodejs 搭建https服务器(二)
来源:互联网 发布:php输出100以内的素数 编辑:程序博客网 时间:2024/06/06 02:05
3. Node搭建https服务器
3.1 配置express项目
$ cd /Users/51testing/Desktop/https
$ express HttpsService
.... install dependencies:
$ cd HttpsService && npm install run the app:
$ DEBUG=httpsservice:* npm start
$ cd HttpsService && npm install .....
执行完毕后的目录如下:
3.2 配置文件
创建目录certificate,将创建的文件拖入进去,
3.3 编写代码
express默认采用http协议,在bin/www目录下配置入口文件;
我们在app.js文件中配置https服务器, nodejs默认存在http与https模块,直接引用即可.
#app.js中加入如下代码:
var app = express(); //使用nodejs自带的http、https模块
var https = require('https');
var http = require('http');
var fs = require('fs');
//根据项目的路径导入生成的证书文件
var privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.pem'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, './certificate/ca.cer'), 'utf8');
var credentials = {key: privateKey, cert: certificate};
//创建http与HTTPS服务器
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
//可以分别设置http、https的访问端口号
var PORT = 8000;
var SSLPORT = 8001;
//创建http服务器
httpServer.listen(PORT, function() {
console.log('HTTP Server is running on: http://localhost:%s', PORT); });
//创建https服务器
httpsServer.listen(SSLPORT, function() {
console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); }); //可以根据请求判断是http还是https
app.get('/', function (req, res) {
if(req.protocol === 'https') {
res.status(200).send('This is https visit!');
} else {
res.status(200).send('This is http visit!');
}
});
3.4 验证
启动服务:
$ node bin/www
HTTP Server is running on: http://localhost:8000
HTTPS Server is running on: https://localhost:8001
**打开浏览器访问: https://localhost:8001
**点击继续-高级--访问不安全链接:
**访问http服务器: http://localhost:8000
- Nodejs 搭建https服务器(二)
- Nodejs 搭建https服务器(一)
- nodejs 搭建https服务
- Nodejs创建HTTPS服务器
- nodejs 创建https服务器
- Nodejs创建HTTPS服务器
- Nodejs创建HTTPS服务器
- Nodejs创建HTTPS服务器
- Nodejs创建HTTPS服务器
- Nodejs+Express创建HTTPS服务器
- Nodejs+Express创建HTTPS服务器
- Nodejs+Express创建HTTPS服务器
- nodejs web应用服务器搭建(二):express 框架说明(应用)
- nodejs搭建http服务器(单一响应)
- nodejs服务器搭建
- 搭建本地nodeJs服务器
- nodejs搭建web服务器
- nodejs搭建web服务器
- 去掉Mybatis Generator生成的一堆 example
- 请求WebService出现"因 URL 意外地以 结束,请求格式无法识别"解决方法
- jquery动态加载js文件
- C++第五次上机--作业报告
- 【LeetCode】154. Find Minimum in Rotated Sorted Array II
- Nodejs 搭建https服务器(二)
- Iframe自适应高度
- UEditor添加一个普通按钮及其他使用注意事项
- 欢迎使用CSDN-markdown编辑器
- Windows7与Window2008 64位IIS7上面DCOM配置Excel、Word等
- hrbust 1864人类希望——kokoⅠ【数学+快速幂】
- 无刷新上传
- React Native (五):上下拉刷新加载
- 网络传输压缩DLL: ICSharpCode.SharpZipLib