我似乎找不到任何关于通过https运行Svelte应用程序的信息。我想在 https 上运行 dev 和 prod。我能够在 package.json 的脚本中使用--port
参数更改端口,但显然这不会将协议从 http 更改为 https。
您需要从某个地方(如ZeroSSL(创建SSL证书。如果您已经有certificate.crt
和private.key
文件,请编辑您的server.js
文件。
<sapper project directory>/src/server.js
的原始源代码是:
import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
polka() // You can also use Express
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
您可以添加和更改此文件(server.js
(的某些代码,如下所示:
import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const { createServer } = require('https');
const { readFileSync } = require('fs');
const ssl_port = 443;
const options = {
// The path & file names could be different.
key: readFileSync('/home/ubuntu/ssl/private.key'),
cert: readFileSync('/home/ubuntu/ssl/certificate.crt')
};
const { handler } = polka()
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.get('*', (req, res) => {
res.end(`POLKA: Hello from ${req.pathname}`);
});
// Mount Polka to HTTPS server
createServer(options, handler).listen(ssl_port, _ => {
console.log(`> Running on https://localhost:${ssl_port}`);
});
添加的代码是:
const { createServer } = require('https');
const { readFileSync } = require('fs');
const ssl_port = 443;
const options = {
// The path & file names could be different.
key: readFileSync('/home/ubuntu/ssl/private.key'),
cert: readFileSync('/home/ubuntu/ssl/certificate.crt')
};
更改后的代码是:
const { handler } = polka()
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.get('*', (req, res) => {
res.end(`POLKA: Hello from ${req.pathname}`);
});
// Mount Polka to HTTPS server
createServer(options, handler).listen(ssl_port, _ => {
console.log(`> Running on https://localhost:${ssl_port}`);
});
然后,由于端口 443 的权限,您必须使用sudo
运行 Svelte/Sapper 应用程序。(像这样:sudo npm run dev
或sudo npm run start
(
运行sudo npm run dev
后,您可能会看到以下消息:
$ sudo npm run dev
> TODO@0.0.1 dev /home/ubuntu/ensayar-sapper
> sapper dev
✔ server (2.1s)
✔ client (2.1s)
> Running on https://localhost:443
✔ service worker (42ms)
> Server is not listening on port 3000
您可以忽略消息Server is not listening on port 3000
。
这与工兵有关。只需使用服务器框架的选项。你使用快递还是波尔卡?按照他们的指示!
到目前为止,似乎唯一的方法是在Svelte/Sapper应用程序之前运行反向代理(如nginx(。
爱因斯坦:对不起...这是一段时间内唯一的答案。我应该删除这个还是什么?