利用 deno.dev 反代解决前端跨域以及 https 网页无法调用 http api 的问题
import { serve } from "https://deno.land/[email protected]/http/server.ts"const suffixWhiteList = [
'shuzijumin.com',
'localhost',
'127.0.0.1',
]
serve(async (req: Request) => {
const url = new URL(req.url)
const targetUrl = url.href.replace(`${url.origin}/`, '')
let urlObj: URL
try {
urlObj = new URL(targetUrl)
let ifHostInWhiteList = false
for (const suffix of suffixWhiteList) {
if (urlObj.hostname.toLowerCase().endsWith(suffix)) {
ifHostInWhiteList = true
break
}
}
if (!ifHostInWhiteList) {
return new Response(`hostname suffix not in white list`, {status: 403})
}
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) => {
if (key.toLowerCase()!=='access-control-allow-origin') {
headers = value
}
})
headers['Access-Control-Allow-Origin'] = '*'
return new Response(res.body, { headers, status: res.status })
}
} catch (e) {
console.error(e.message)
}
return new Response(`Usage: ${url.origin}/https://deno.com/deploy/docs/pricing-and-limits`)
})
页:
[1]