You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit/Vite本地自签名证书问题:Fetch删除用户时报错

问题解决指南

一、basicSsl插件下fetch删除用户报错的修复

你当前代码存在两个核心问题:

  1. disconnect回调未声明async:socket.on('disconnect', () => {) 内部使用了await,但箭头函数未添加async关键字,会导致语法错误,同时影响Agent的正常生效。
  2. 缺少JSON请求头:发送JSON格式的请求体时,未指定Content-Type: application/json头,后端可能无法正确解析请求数据。

修复后的代码片段:

plugins: [
    basicSsl(),
    sveltekit(),
    {
        name: 'sveltekit-socket-io',
        configureServer(server) {
            const io = new Server(server.httpServer);
            io.on('connection', (socket) => {
                const agent = new https.Agent({
                    rejectUnauthorized: false
                });
                // 给回调添加async关键字
                socket.on('disconnect', async () => {
                    try {
                        await fetch('https://localhost:5173/api/users', {
                            method: 'DELETE',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ id: socket.uid }),
                            agent: agent
                        });
                    } catch (err) {
                        console.error('删除用户失败:', err);
                    }
                });
            });
        }
    }
]

二、mkcert证书导致浏览器ERR_SSL_VERSION_OR_CIPHER_MISMATCH的修复

该错误通常是Vite加载证书的方式错误,或证书加密套件不兼容浏览器,按以下步骤处理:

  1. 生成兼容的mkcert证书:
    执行mkcert localhost生成localhost.pem和localhost-key.pem文件,确保密钥长度不低于2048位(mkcert默认满足)。
  2. 在Vite中手动配置证书:
    移除basicSsl插件,在vite.config.js中指定证书路径:
    import { sveltekit } from '@sveltejs/kit/vite';
    import { defineConfig } from 'vite';
    
    export default defineConfig({
        plugins: [sveltekit()],
        server: {
            https: {
                key: './localhost-key.pem',
                cert: './localhost.pem'
            }
        }
    });
    
  3. 清除缓存并重启服务:
    完全关闭浏览器后重新打开,避免旧SSL缓存干扰;同时重启Vite开发服务器,确保新配置生效。
  4. 安装mkcert根证书:
    执行mkcert -install将根证书添加到系统信任存储,解决浏览器证书不信任问题(此步骤不直接修复版本/套件错误,但能避免后续关联问题)。

内容的提问来源于stack exchange,提问作者ndru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:01:26