簡體   English   中英

帶有 ssl 和靜態文件服務的 node.js

[英]node.js with ssl and static files serving

我有一個問題,當我添加app.use(express.static(__dirname + '/public'))時,我無法設置支持 ssl 的節點 js 服務器並且還可以通過此 ssl 提供靜態文件這些文件是從 https 常規服務器提供的。 有人試圖這樣做嗎?

//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);
    });
}

嘗試這個:

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

好的,我知道了。 因為我使用 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>

參考: 如何在 Azure 網站中的 node.js 上強制 express 使用 https?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM