jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

node同时创建http服务和https服务 #48

Open jackieli123723 opened 6 years ago

jackieli123723 commented 6 years ago

node同时创建http服务和https服务让测试服用http,正式服务器用https加密传输协议,数据传输的时候不会被窃取一般来说安全系数更高。也是现在流行的做法

测试服 http://gm.test.dragonest.com/login

正式服 https://gm.dragonest.com/#/login

//这是贴出的核心代码可以把mongo或者mysql的代码自行添加

"use strict";
var app = require('express')();
var fs = require('fs');
var http = require('http');
var https = require('https');
var request = require('request');
var bodyParser = require('body-parser');
var privateKey  = fs.readFileSync('./private.pem', 'utf8');
var certificate = fs.readFileSync('./file.crt', 'utf8');
var caKey = fs.readFileSync('./csr.pem', 'utf8');
var credentials = {key: privateKey, ca:[caKey], cert: certificate};
//生成了三个文件:private.pem: 私钥、csr.pem: CSR证书签名、file.crt: 证书文件。
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 1110;
var SSLPORT = 1111;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

httpServer.listen(PORT, function() {
    console.log('http://localhost:%s', PORT);
});
httpsServer.listen(SSLPORT, function() {
    console.log('https://localhost:%s', SSLPORT);
});

function httpsPostResult(url, json, res) {
    request.post(url, { json:json },
        function (_error, response, body) {
            if (!_error && response.statusCode == 200) {
                res.json(body);
            }else {
                console.log('报错了');
            }
        }
    );
}

app.get('/', function(req, res) {
    if(req.protocol === 'https') {
        res.status(200).send('https');
    } else {
        res.status(200).send('http');
    }
});
var host = '';
/**
 * api
 */
app.post('/jackieli',function (req, res, next) {
    var url = host + '/jackieli';
    var json = {
        mobile:req.body.mobile
    };
    httpsPostResult(url, json, res);
});