前端在调用别人 api 时经常遇到跨域或者 https 无法调用 http 的问题,通过反代即可解决
deno.com 提供免费的 NodeJS 环境,在其官网后台新建应用,在 playground 粘贴代码:

import { serve } from "https://deno.land/[email protected]/http/server.ts"
serve(async (req: Request) => {
  const url = new URL(req.url)
  const targetUrl = url.href.replace(`${url.origin}/`, '')
  let urlObj: any
  try {
    urlObj = new URL(targetUrl)
  } catch (e) {
    console.error(e.message)
  }
  if (['http:', 'https:'].indexOf(urlObj?.protocol) > -1) {
    let res = await fetch(targetUrl, {
      headers: req.headers,
      method: req.method,
      body: req.body,
    })
    let headers = {}
    res.headers.forEach((value, key) => {
      headers[key] = value
    })
    if ('*' !== headers['Access-Control-Allow-Origin']?.trim()
      && '*' !== headers['access-control-allow-origin']?.trim()) {
      headers['Access-Control-Allow-Origin'] = '*'
    }
    return new Response(res.body, { headers, status: res.status })
  }
  return new Response(
    `Usage: ${url.origin}/https://deno.com/deploy/docs/pricing-and-limits`)
})

优势:跟cloudflare worker相比,这个支持带端口的url

添加新评论