NodeJS+Express搭建RESTful api服务,且配置https服务

安装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

创建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!!");
});

启动服务

# 启动服务
node app.js
# 后台启动服务
nohup node app.js &

到此为止,已经成功的创建了一个http的服务器,并且提供了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

之后就会生成下面几个文件,具体位置会有提示

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!');
    }
});

你可能感兴趣的:(NodeJS+Express搭建RESTful api服务,且配置https服务)