简体   繁体   English

带有 ssl 和静态文件服务的 node.js

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

I have a problem which I can't manage to set a node js server that support ssl and also can serve static files over this ssl, when I am adding the app.use(express.static(__dirname + '/public')) the files are being serve from https regular server.我有一个问题,当我添加app.use(express.static(__dirname + '/public'))时,我无法设置支持 ssl 的节点 js 服务器并且还可以通过此 ssl 提供静态文件这些文件是从 https 常规服务器提供的。 some one has tried to do that?有人试图这样做吗?

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

Try this:尝试这个:

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

Ok, Got it.好的,我知道了。 Becouse i am using Azure as my hosting provider, Azure is taken care all of the SSL support for you, so i didn't needed to create a dedicated https server:因为我使用 Azure 作为我的托管服务提供商,Azure 会为您提供所有 SSL 支持,所以我不需要创建专用的https服务器:

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

All i needed to do is to add my web.config the following code - a permanent redirect to the https url.我需要做的就是在我的 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?参考: 如何在 Azure 网站中的 node.js 上强制 express 使用 https?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM