安裝nodejs
sudo apt-get install nodejs
sudo apt install nodejs-legacy
sudo apt install npm
初始化
mkdir webservices
cd webservices
npm init
安裝express
sudo npm install express
創(chuàng)建app.js
var express = require("express")
var app = express();
app.get("/hello",function (req,resp) {
resp.send("hello express!");
});
app.listen(80,function () {
console.log("server start!!");
});
啟動(dòng)服務(wù)
# 啟動(dòng)服務(wù)
node app.js
# 后臺(tái)啟動(dòng)服務(wù)
nohup node app.js &
到此為止尚骄,已經(jīng)成功的創(chuàng)建了一個(gè)http的服務(wù)器,并且提供了RESTful Api侵续。
安裝ssl證書倔丈,https訪問
安裝certbot
https://certbot.eff.org/lets-encrypt/ubuntuxenial-other
$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository universe
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install certbot
生成證書
$ sudo certbot certonly --standalone -d example.com
之后就會(huì)生成下面幾個(gè)文件憨闰,具體位置會(huì)有提示
cert.pem
chain.pem
fullchain.pem
privkey.pem
修改app.js
https://medium.com/@yash.kulshrestha/using-lets-encrypt-with-express-e069c7abe625
https://medium.com/%E5%89%8D%E7%AB%AF%E5%A3%B9%E5%85%A9%E4%B8%89%E4%BA%8B/nodejs-express-10-%E5%88%86%E9%90%98%E7%94%B3%E8%AB%8B-letsencrypt-6a1fc2bce4fb
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
// Set up express server here
const options = {
cert: fs.readFileSync('你自己的路徑/fullchain.pem'),
key: fs.readFileSync('你自己的路徑/privkey.pem')
};
app.listen(80);
https.createServer(options, app).listen(443);
// Welcome
app.get('/', function(req, res) {
if(req.protocol === 'https') {
res.status(200).send('Welcome to Safety Land!');
} else {
res.status(200).send('Welcome!');
}
});