estk
V2EX  ›  Node.js

Deno 反向代理解决前端跨域问题以及将 http 转为 https

  •  
  •   estk · Oct 28, 2022 · 7242 views
    This topic created in 1293 days ago, the information mentioned may be changed or developed.

    前端在调用别人 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`)
    })
    
    13 replies    2022-11-19 13:18:51 +08:00
    learningman
        1
    learningman  
       Oct 29, 2022
    可别拿人家测试环境当云函数使了。。。
    8520ccc
        2
    8520ccc  
       Oct 29, 2022 via iPhone
    @learningman 不滥用,厂家是支持的……
    amlee
        3
    amlee  
       Oct 29, 2022
    @learningman 本身就是一个云函数环境呀,有额度的
    icoming
        4
    icoming  
       Oct 29, 2022
    比如说,反代百度可以正常打开首页,但点击搜索后,跳转时就把百度的域名给弄丢了。这个怎么搞?
    c0t
        5
    c0t  
       Oct 29, 2022 via Android
    deno 到底是禁止反代,还是禁止破墙的代理?
    estk
        6
    estk  
    OP
       Oct 29, 2022 via Android
    @icoming #4
    这个需要把 html 代码里的所有 src 再反代一下,需要处理源码
    estk
        7
    estk  
    OP
       Oct 29, 2022 via Android
    @c0t #5
    deno 哪个官方文档提到禁止反代?
    icoming
        8
    icoming  
       Oct 29, 2022
    @estk 谢谢,偶尔急用还是很不错
    estk
        9
    estk  
    OP
       Oct 29, 2022 via Android
    @icoming #8
    当你们公司后端给你测试接口不开跨域时
    icoming
        11
    icoming  
       Oct 29, 2022
    @Lighfer 谢谢,可用。这小玩意挺有意思
    dumbass
        12
    dumbass  
       Oct 30, 2022 via iPhone
    前端构建工具自带有 proxy 啊
    c0t
        13
    c0t  
       Nov 19, 2022 via Android   ❤️ 1
    @estk https://deno.com/deploy/docs/fair-use-policy 倒也不是说禁止,不建议当 proxy 用
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5478 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 66ms · UTC 07:50 · PVG 15:50 · LAX 00:50 · JFK 03:50
    ♥ Do have faith in what you're doing.