node 后臺 app.js配置
const express = require('express') //加載express資源
const bodyParser=require("body-parser")//一個Express中間件,用于解析HTTP請求體,獲得請求的數(shù)據(jù)
const app = express() //返回一個express服務器對象
const https = require('https')
const fs = require('fs')
const path = require('path');
const logger=require("morgan");//日志模塊
const favicon=require("serve-favicon") //用于設置和提供 favicons(網(wǎng)頁標簽圖標)。
const WebSocket = require('ws')
//導入ajaxRouter這個路由
const route=require("./routes/backmtage/ajaxRouter")
const route1=require("./routes/appoet/ajaxRouter");
// 日志模塊放在最上方
app.use(logger("dev"))//調用日志,配置為dev(開發(fā))模式
// 使用bodyParser應該在路由前
// extended:false:表示使用系統(tǒng)模塊query string來處理數(shù)據(jù)
// extended:true 表示使用第三方模塊qs來處理
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//使用路由,放在靜態(tài)資源路徑前面
app.use(route)
app.use(route1)
//設置靜態(tài)資源路徑
//__dirname指向當前文件的根目錄
app.use(express.static(__dirname+"/public"))
//設置小圖標
app.use(favicon(__dirname+"/public/images/favicon.ico"))
//ssl證書
const options = {
key:fs.readFileSync(path.join(__dirname,'./ssl/xxxxxx.cn.key')),
cert:fs.readFileSync(path.join(__dirname,'./ssl/xxxxxx.cn.pem'))
}
//創(chuàng)建https服務器
const httpsServer = https.createServer(options,app,(req,res)=>{
res.writeHead(200, { 'Content-Type': 'text/html;charset=utf8' });
res.end('This is a https server!\n')
})
httpsServer.listen(8886, () => {
// console.log('服務已開啟8886');
console.log('HTTPS Server is running on: https://xxxx.com:%s', 9999);
})
const wss = new WebSocket.Server(
{
server:httpsServer
},
()=>{
console.log('socket start');
}
)
//建立連接
wss.on('connection',ws=>{
//接收數(shù)據(jù)
ws.on('message',data=>{
console.log('received:%s',data);
})
ws.send('something')
})
服務啟動后控制臺輸出:
?測試:服務器連接
瀏覽器輸入:https:xxxxx:端口 訪問成功?
?測試wss? ?
可以在這個網(wǎng)站websocket/ws/wss在線調試測試工具
發(fā)送消息 看服務端?
參考:node搭建本地https和wss服務(SSL證書安全)_node ssl_jixhua的博客-CSDN博客文章來源:http://www.zghlxwxcb.cn/news/detail-540213.html
Node.js網(wǎng)絡編程之WebSocket篇_node websocket_夜已如歌_ok的博客-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-540213.html
到了這里,關于node搭建本地https和wss服務(SSL證書安全)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!