標籤:require modules func module console host res erro str
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.mobile55 };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啟動服務
nodejs,調用介面修改https