函数代码如下:
// 目标url和host
const someHost = ‘www.example.com’
const someUrl = ‘https://www.example.com/json’
async function handleRequest(request) {
let newRequestInit = {
method: ‘GET’,
headers: {
‘Content-Type’: ‘application/json’,
}
}
// 设置新的url和host
url = new URL(someUrl)
url.hostname = someHost
// 新建请求
const newRequest = new Request(url, new Request(request, newRequestInit))
newRequest.headers.set(‘Content-Type’, ‘application/json’)
try {
// 发送请求并返回结果
return await fetch(newRequest)
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500 })
}
}
addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/courses/249398.html