百度云加速边缘计算函数应用实例:修改原始请求

函数代码如下:

// 目标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))
})

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
个人中心
购物车
优惠劵
搜索