1。快速开始
如果我们想把请求HOOK住,我们需要一个一定的TRIGGER;此地我们的TRIGGER是addEventListener(),也就是我们任何功能的入口,我们日常都按照一般来说方式HOOK住请求。
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event))
})
我们就大好在handleRequest法门中,实现我们想要的逻辑。其中我们日常需要拿到请求的情节request。request包含在event内。大好按照一般来说方式到手;request对象中,包含了url,headers,method等属性,比如我们想到手url,则大好按照一般来说方式到手;例如。我们想根据不可同日而语url返回不可同日而语的情节,则大好照章url进行判断并返回不可同日而语情节。
async function handleRequest(event) {
const { request } = event
const { url } = request
if (url.endsWith('/router1')) {
return rawJsonResponse({result: 'a'})
}
if (url.endsWith('/router2')) {
return rawJsonResponse({result: 'b'})
}
}
我们需要构造一个response返回给连通器;为着返回能够被连通器正确显示,我们需要指定content-type,大好按照一般来说方式指定headers中的content-type;通过new一个Response对象,我们大好生成一个返回,并把headers信息添加进去。就大好生成一个返回。
async function rawJsonResponse(json) {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response(JSON.stringify(json), init)
}
我们完成了一个到手请求-根据请求执行不可同日而语逻辑-生成返回并返回的流程,完整代码翻译一般来说。
async function rawJsonResponse(json) {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response(JSON.stringify(json), init)
}
async function rawJsonResponse(json) {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response(JSON.stringify(json), init)
}
async function handleRequest(event) {
const { request } = event
const { url } = request
if (url.endsWith('/router1')) {
return rawJsonResponse({ result: 'a' })
}
if (url.endsWith('/router2')) {
return rawJsonResponse({ result: 'b' })
}
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event))
})
2,函数短信接口提供商
addEventListener(type, event => {…}))
参数说明书
type: type固定为’fetch’。 event: event包含三个法门,respondWith(),passThroughOnException()。waitUntil()。 respondWith()法门为请求供给自定义的返回。 passThroughOnException()法门会在代码翻译出现非同寻常时直接从源站到手情节,以避免代码翻译非同寻常感应正常访问。 waitUntil()法门大好延绵时间的怒放的生命周期。当代码翻译逻辑里存在一呼百应时间较长的其他服务配用时,大好采用该法门。
new Request(input [, init])
参数说明书
input: 可传URL或Request对象。当你想修改URL时,需在此参数位置传入URL。但你想修改其他属性时,此参数位置传入已存在的Request对象以传承属性。
init (可选): 修改Request属性时,可传入需要修改的参数。可选参数一般来说: method: 请求法门,如GET,POST。 headers: 请求头。 body: 请求数据。当请求法门为GET或HEAD时。Request不包含body。 redirect: 重定向方式,可选follow, error, or manual。公认为manual。
new Response(body, init)
参数说明书
body (可选): Response的body,大好是以下方式中的一种: BufferSource FormData ReadableStream URLSearchParams USVString init (可选): 大好自定义Response的属性。 status: 状况码。比如:200。 statusText: 状况,比如:OK。 headers: Response的headers。
没有更多动态情节大好参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API
https://developer.mozilla.org/zh-CN/docs/Web/API/Request/Request
https://developer.mozilla.org/zh-CN/docs/Web/API/Response/Response