1 "use strict"; 2 3 var app = require(‘express‘)(); 4 var fs = require(‘fs‘); 5 var http = require(‘http‘); 6 var https = require(‘https‘); 7 var request = require(‘request‘); 8 var bodyParser = require(‘body-parser‘); 9 var privateKey = fs.readFileSync(‘./private.pem‘, ‘utf8‘); 10 var certificate = fs.readFileSync(‘./file.crt‘, ‘utf8‘); 11 var caKey = fs.readFileSync(‘./csr.pem‘, ‘utf8‘); 12 var credentials = {key: privateKey, ca:[caKey], cert: certificate}; 13 14 var httpServer = http.createServer(app); 15 var httpsServer = https.createServer(credentials, app); 16 var PORT = 1110; 17 var SSLPORT = 1111; 18 app.use(bodyParser.json()); 19 app.use(bodyParser.urlencoded({extended: true})); 20 21 httpServer.listen(PORT, function() { 22 console.log(‘http://localhost:%s‘, PORT); 23 }); 24 httpsServer.listen(SSLPORT, function() { 25 console.log(‘https://localhost:%s‘, SSLPORT); 26 }); 27 28 function httpsPostResult(url, json, res) { 29 request.post(url, { json:json }, 30 function (_error, response, body) { 31 if (!_error && response.statusCode == 200) { 32 res.json(body); 33 }else { 34 console.log(‘报错了‘); 35 } 36 } 37 ); 38 } 39 40 app.get(‘/‘, function(req, res) { 41 if(req.protocol === ‘https‘) { 42 res.status(200).send(‘https‘); 43 } else { 44 res.status(200).send(‘http‘); 45 } 46 }); 47 var host = ‘‘; 48 /** 49 * 短信验证码 50 */ 51 app.post(‘/test‘,function (req, res, next) { 52 var url = host + ‘/test‘; 53 var json = { 54 mobile:req.body.mobile 55 }; 56 httpsPostResult(url, json, res); 57 });
生成了三个文件:private.pem: 私钥、csr.pem: CSR证书签名、file.crt: 证书文件。
创建 : package.json
1 { 2 "name": "application-name", 3 "version": "0.0.1", 4 "dependencies":{ 5 "body-parser": "latest", 6 "express": "latest", 7 "request": "latest" 8 } 9 }
npm install 安装 node_modules
node启动服务
时间: 2024-11-08 22:25:38