Telegram Mini App无法向本地服务器请求的问题求助
移动端Telegram Mini App请求本地服务器的HTTPS/HTTP问题
我的项目包含三个模块:
- bot:仅用于启动Telegram Mini App
- client:基于Vite的网页项目
- server:Express后端服务,集成Sequelize操作数据库
问题现象
桌面端Telegram打开Mini App时,请求能正常发送到本地http://localhost:3000服务器;但移动端打开时,发送HTTP请求会触发ERR_CLEARTEXT_NOT_PERMITTED错误。
排查与尝试
确认移动端仅支持HTTPS请求后,我用openssl生成了SSL证书,但将客户端请求切换为https://localhost:3000后,又出现net::ERR_CONNECTION_REFUSED错误。
以下是我的服务器代码:
import express, { Request, Response } from "express"; import sequelize from "./config/database"; import { User } from "./models/user"; import cors from "cors"; import https from "https"; import * as fs from "fs"; import * as path from "path"; const app = express(); const port = 3000; app.use(express.json()); const corsOptions = { origin: "http://localhost:5173", credentials: true, //access-control-allow-credentials:true optionSuccessStatus: 200, }; app.use(cors(corsOptions)); // Use this after the variable declaration app.get("/", async (req: Request, res: Response) => { res.send("Hello World!"); }); app.post("/user", async (req: Request, res: Response) => { const { first_name, username, id } = req.body; console.log(req.body); try { // Check if user already exists const existingUser = await User.findOne({ where: { id } }); if (existingUser) { return res.status(409).json({ error: "User already exists" }); } // Create new user const user = await User.create({ first_name, username, id }); res.status(201).json(user); } catch (error) { res.status(400).json({ error: error.message }); } }); console.log(__dirname); const options = { key: fs.readFileSync(path.resolve(__dirname, "../cert/key.pem")), cert: fs.readFileSync(path.resolve(__dirname, "../cert/cert.pem")), }; // app.set("ssl", true); // app.set("sslKey", options.key); // app.set("sslCert", options.cert); const start = async () => { try { await sequelize.authenticate(); console.log("Database connected!"); await sequelize.sync({ force: true }); // This will drop existing tables and re-create them // const server = https.createServer(options, app); // server.listen(port, () => { // console.log("Express server listening on port " + port + ", secure = " + true); // }); app.listen(port, () => { console.log("Express server listening on port " + port + ", secure = " + true); }); } catch (error) { console.error("Unable to connect to the database:", error); } }; start();
疑问
- 切换为HTTPS后出现连接拒绝错误,是否是SSL证书的问题?
- 有没有其他方法可以解决移动端的
ERR_CLEARTEXT_NOT_PERMITTED错误?
备注:客户端是Vite网页项目,并非Android Studio原生项目。
内容的提问来源于stack exchange,提问作者Артем Липник
相关产品推荐
相关产品推荐

