一.使用 Node 和 Express 搭建一個(gè) HTTP 服務(wù)器
1.在app.js修改小程序通信域名
App({
config: {
host: '' // 這個(gè)地方填寫(xiě)你的域名
},
onLaunch () {
console.log('App.onLaunch()');
}
});
2.安裝 NodeJS 和 NPM
yum install nodejs npm -y
node -v
3.編寫(xiě)HTTP服務(wù)源碼
touch package.json
#文件內(nèi)容
{
"name": "weapp",
"version": "1.0.0"
}
touch app.js
#文件內(nèi)容
// 引用 express 來(lái)支持 HTTP Server 的實(shí)現(xiàn)
const express = require('express');
// 創(chuàng)建一個(gè) express 實(shí)例
const app = express();
// 實(shí)現(xiàn)唯一的一個(gè)中間件,對(duì)于所有請(qǐng)求,都輸出 "Response from express"
app.use((request, response, next) => {
response.write('Response from express');
response.end();
});
// 監(jiān)聽(tīng)端口,等待連接
const port = 8765;
app.listen(port);
// 輸出服務(wù)器啟動(dòng)日志
console.log(`Server listening at http://127.0.0.1:${port}`);
4.運(yùn)行 HTTP 服務(wù)
安裝 PM2
npm install pm2 --global
注:PM 倉(cāng)庫(kù)在國(guó)內(nèi)訪(fǎng)問(wèn)速度可能不太理想,如果實(shí)在太慢可以嘗試使用 CNPM 的 Registry 進(jìn)行安裝:npm install pm2 -g --registry=https://r.cnpmjs.org/
安裝 Express
npm install express --save
服務(wù)管理
啟動(dòng)服務(wù)
pm2 start app.js
#查看服務(wù)輸出的日志
pm2 logs
#重啟服務(wù)
pm2 restart app
二.利用nginx和SSL證書(shū)搭建HTTPS服務(wù)
1.安裝與啟動(dòng)
#安裝
yum install nginx -y
#啟動(dòng)
nginx
2.配置HTTPS
外網(wǎng)用戶(hù)訪(fǎng)問(wèn)服務(wù)器的 Web 服務(wù)由 Nginx 提供,Nginx 需要配置反向代理才能使得 Web 服務(wù)轉(zhuǎn)發(fā)到本地的 Node 服務(wù)。
上傳證書(shū)
nginx
#conf文件內(nèi)容
server {
listen 443;
server_name www.example.com; # 改為綁定證書(shū)的域名
#ssl 配置
ssl on;
ssl_certificate 1_www.example.com_bundle.crt; # 改為自己申請(qǐng)得到的 crt 文件的名稱(chēng)
ssl_certificate_key 2_www.example.com.key; # 改為自己申請(qǐng)得到的 key 文件的名稱(chēng)
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://127.0.0.1:8765;
}
}
#nginx重新加載配置文件
nginx -s reload