gpt4 book ai didi

ssl - 如何通过 HTTPS/SSL 运行 Svelte/Sapper 应用程序?

转载 作者:行者123 更新时间:2023-12-04 02:40:01 24 4
gpt4 key购买 nike

我似乎找不到任何有关通过 https 运行 Svelte 应用程序的信息。我想在 https 上为 dev 和 prod 运行。我可以在 package.json 的脚本中使用 --port 参数更改端口,但显然这不会将协议(protocol)从 http 更改为 https。

最佳答案

你需要从某个地方创建 SSL 证书(比如 ZeroSSL )。如果你已经有 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}`);
});

然后您必须使用 sudo 运行您的 Svelte/Sapper 应用程序因为端口 443 的权限。(像这样: sudo npm run devsudo 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 .

关于ssl - 如何通过 HTTPS/SSL 运行 Svelte/Sapper 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com