前端在调用别人 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`)
})
1
learningman 2022-10-29 02:57:42 +08:00
可别拿人家测试环境当云函数使了。。。
|
2
8520ccc 2022-10-29 03:28:44 +08:00 via iPhone
@learningman 不滥用,厂家是支持的……
|
3
amlee 2022-10-29 04:47:52 +08:00
@learningman 本身就是一个云函数环境呀,有额度的
|
4
icoming 2022-10-29 06:53:14 +08:00
比如说,反代百度可以正常打开首页,但点击搜索后,跳转时就把百度的域名给弄丢了。这个怎么搞?
|
5
c0t 2022-10-29 09:20:19 +08:00 via Android
deno 到底是禁止反代,还是禁止破墙的代理?
|
10
Lighfer 2022-10-29 21:40:40 +08:00 1
|
12
bojackhorseman 2022-10-30 00:18:13 +08:00 via iPhone
前端构建工具自带有 proxy 啊
|
13
c0t 2022-11-19 13:18:51 +08:00 via Android 1
@estk https://deno.com/deploy/docs/fair-use-policy 倒也不是说禁止,不建议当 proxy 用
|