将React应用转为PWA后无法访问Express API的问题求助
问题
我在共享主机上运行React应用和Express.js服务器。转成PWA之前,能通过网站URL的/api路径正常访问API,但转换为PWA后,无法获取API响应,浏览器持续显示加载状态。项目使用Vite开发,以下是我的PWA配置代码:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { VitePWA } from "vite-plugin-pwa"; const manifestForPlugin = { registerType: "prompt", includeAssets: ["favicon.ico", "apple-touch-icon.png", "masked-icon.svg"], manifest: { name: "Alibot.ir", short_name: "Alibot", description: "My personal website.", icons: [ { src: "/android-chrome-192x192.png", sizes: "192x192", type: "image/png", }, { src: "/android-chrome-512x512.png", sizes: "512x512", type: "image/png", }, { src: "/apple-touch-icon.png", sizes: "180x180", type: "image/png", purpose: "apple touch icon", }, { src: "/maskable_icon.png", sizes: "225x225", type: "image/png", purpose: "any maskable", }, ], theme_color: "#171717", background_color: "#e8ebf2", display: "standalone", scope: "/", start_url: "/", orientation: "portrait", }, }; // https://vitejs.dev/config/ export default defineConfig({ base: "./", plugins: [react(), VitePWA(manifestForPlugin)], });
错误截图:
解决方案
1. 让Service Worker跳过API请求拦截
问题核心是VitePWA默认的Service Worker缓存规则拦截了/api请求,导致无法转发到Express服务器。修改PWA配置,添加Workbox规则排除API路径:
const manifestForPlugin = { // 保留原有manifest配置不变 registerType: "prompt", includeAssets: ["favicon.ico", "apple-touch-icon.png", "masked-icon.svg"], manifest: { /* ... 原有内容 ... */ }, // 添加Workbox配置 workbox: { // 直接排除所有/api开头的请求,不让Service Worker处理 exclude: [/^\/api/], // 若需要缓存API响应,可设置优先网络的策略 runtimeCaching: [ { urlPattern: /^\/api/, handler: 'NetworkFirst', options: { cacheName: 'api-cache', cacheableResponse: { statuses: [0, 200] } } } ] } };
2. 修正base路径配置
当前base: "./"会让资源使用相对路径,可能导致API请求路径解析错误。如果应用部署在域名根目录,将base改为根路径:
export default defineConfig({ base: "/", // 替换原有的"./" plugins: [react(), VitePWA(manifestForPlugin)], });
若部署在子目录,需确保base值与API路径的相对关系匹配。
3. 清除旧缓存
部署新配置后,手动清除浏览器缓存以加载最新配置:
- Chrome:打开开发者工具 → Application → Service Workers → 点击"Unregister",同时清除Cache Storage下的缓存。
- 其他浏览器执行类似操作,确保旧的Service Worker和缓存被完全清除。
内容的提问来源于stack exchange,提问作者AliBot
相关产品推荐
相关产品推荐

