找回密码
 注册免广告
搜索
人人必备的 Wise 💳华侨银行送 15 新加坡币 🎁个人 IBAN 出金,注册送 $25 比特币 ฿数字货币银行卡,注册送 7 美元💲
查看: 439|回复: 0

利用 deno.dev 反代解决前端跨域以及 https 网页无法调用 http api 的问题

[复制链接]

465

主题

5019

回帖

1万

积分

版主

积分
12108
HelloWorld 发表于 2023-6-9 20:02:23 | 显示全部楼层 |阅读模式
  1. import { serve } from "https://deno.land/[email protected]/http/server.ts"
  2. const suffixWhiteList = [
  3.   'shuzijumin.com',
  4.   'localhost',
  5.   '127.0.0.1',
  6. ]
  7. serve(async (req: Request) => {
  8.   const url = new URL(req.url)
  9.   const targetUrl = url.href.replace(`${url.origin}/`, '')
  10.   let urlObj: URL
  11.   try {
  12.     urlObj = new URL(targetUrl)
  13.     let ifHostInWhiteList = false
  14.     for (const suffix of suffixWhiteList) {
  15.       if (urlObj.hostname.toLowerCase().endsWith(suffix)) {
  16.         ifHostInWhiteList = true
  17.         break
  18.       }
  19.     }
  20.     if (!ifHostInWhiteList) {
  21.       return new Response(`hostname suffix not in white list`, {status: 403})
  22.     }
  23.     if (['http:', 'https:'].indexOf(urlObj?.protocol) > -1) {
  24.       let res = await fetch(targetUrl, {
  25.         headers: req.headers,
  26.         method: req.method,
  27.         body: req.body,
  28.       })
  29.       let headers = {}
  30.       res.headers.forEach((value, key) => {
  31.         if (key.toLowerCase()!=='access-control-allow-origin') {
  32.           headers[key] = value
  33.         }
  34.       })
  35.       headers['Access-Control-Allow-Origin'] = '*'
  36.       return new Response(res.body, { headers, status: res.status })
  37.     }
  38.   } catch (e) {
  39.     console.error(e.message)
  40.   }
  41.   return new Response(`Usage: ${url.origin}/https://deno.com/deploy/docs/pricing-and-limits`)
  42. })
复制代码


您需要登录后才可以回帖 登录 | 注册免广告

本版积分规则

排行榜|意见建议|数字居民论坛

GMT+8, 2024-5-20 15:21

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表