const current = 'example1.com' const origin = 'example2.com' addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) asyncfunctionhandleRequest(request) { // new URL object to play with, // based on the one being requested. // e.g. https://domain.com/blog/page var url = newURL(request.url) // set hostname to the place we're proxying requests from url.hostname = origin url.protocol = 'https:'; console.log(url.pathname); // remove the first occurence of /blog // so it requests / of the proxy domain // pass the modified url back to the request, let response = awaitfetch(url, request)
if (request.url.endsWith('.png') ||request.url.endsWith('.jpg')||request.url.endsWith('.css')||request.url.endsWith('.gif')) { return response } let { readable, writable } = newTransformStream() streamBody(response.body, writable) returnnewResponse(readable, response) }
asyncfunctionstreamBody(readable, writable) { let reader = readable.getReader() let writer = writable.getWriter() const decoder = newTextDecoder('utf-8') const encoder = newTextEncoder('utf-8') let body = '' while (true) { const { done, value } = await reader.read() if (done) break
body += decoder.decode(value) }
body = body.replace(newRegExp(current,'g'), origin); await writer.write(encoder.encode(body))
说些什么吧!