您可以在 Cloudflare 的 Worker 中编写一个简单的反向代理,将所有 /api 请求转发到 www.pernalgis.top/api 上。以下是一个简单的示例:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  // 检查请求是否为 /api 开头
  if (request.url.startsWith('https://yourdomain.com/api')) {
    // 构建新的请求 URL
    const url = new URL(request.url)
    url.hostname = 'www.pernalgis.top'
    url.pathname = '/api' + url.pathname.substr(14)
    // 发送代理请求
    const proxyRequest = new Request(url, {
      method: request.method,
      headers: request.headers,
      body: request.body
    })
    const proxyResponse = await fetch(proxyRequest)
    // 将代理响应返回给客户端
    return new Response(proxyResponse.body, {
      status: proxyResponse.status,
      statusText: proxyResponse.statusText,
      headers: proxyResponse.headers
    })
  } else {
    // 如果请求不是 /api 开头,直接从缓存中返回响应
    return fetch(request)
  }
}

将上面的代码复制粘贴到 Cloudflare 的 Worker 代码编辑器中,然后将 'yourdomain.com' 替换为您的域名即可。这样,您的 Vue 应用程序就可以通过 /api 访问您的后端服务了。

Cloudflare Pages 部署 Vue 项目跨域访问后端 API 解决方法

原文地址: https://www.cveoy.top/t/topic/ovSG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录