2017-04-05 78 views
-1

我有一個問題,我無法設置一個節點js服務器,支持ssl,也可以通過此ssl服務靜態文件,當我添加app.use (express.static(__ dirname +'/ public'))這些文件正從https常規服務器提供。 有人試圖這樣做?node.js與ssl和靜態filles服務

//require engines 
var express  = require('express'); 
var session  = require('express-session'); 
var bodyParser = require('body-parser') 

//init express engine 
var app = express(); 

//using 
app.use(bodyParser.json()); 
app.use(express.static(__dirname + '/public')); 

var activeport = process.env.PORT ? process.env.PORT : 4003; 

if (process.env.NODE_ENV === "production") { 

    var fs = require('fs'); 
    var https = require('https'); 

    var options = { 
     key: fs.readFileSync(global.appRoot + '/xxx.pem'), 
     cert: fs.readFileSync(global.appRoot + '/yyy.crt'), 
     passphrase: "123123", 
     requestCert: false, 
     rejectUnauthorized: false 
    }; 

    var server = https.createServer(options, app).listen(activeport, function() { 
     console.log('Server listening on port ' + activeport); 
    }); 
} 
else { 
    app.listen(activeport, function() { 
     console.log('Server listening on port ' + activeport); 
    }); 
} 
+0

你確定你是在生產模式?好像你可能實際上在else塊中 – powerc9000

回答

0

試試這個:

const path = require('path'); // <--- Require this 
app.use(express.static(path.join(__dirname, '/dist'))); 
0

好,知道了。 Becouse我使用Azure的作爲我的託管服務提供商,Azure是照顧所有的SSL支持你,所以沒有需要我來創建一個專用的HTTPS服務器:

var server = https.createServer(options, app).listen(activeport, function() { 
    console.log('Server listening on port ' + activeport); 
}); 

所有我需要做的是添加我的web.config下面的代碼 - 永久重定向到https url。

<!-- Redirect all traffic to SSL --> 
    <rule name="Force HTTPS" enabled="true"> 
     <match url="(.*)" ignoreCase="false" /> 
     <conditions> 
     <add input="{HTTPS}" pattern="off" /> 
     </conditions> 
     <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" /> 
    </rule> 

Referar: How do you force express on node.js in Azure Websites to use https?