1 javascript cloudflare-workers
我想知道是否有人能够帮助弄清楚如何使用 cloudflare 工作人员将帖子正文传递到另一个端点?我正在尝试将传入的请求发布到 url。
const url = 'https://webhook.site/#!/b2f75ce2-7b9e-479a-b6f0-8934a89a3f3d'
const body = {
results: ['default data to send'],
errors: null,
msg: 'I sent this to the fetch',
}
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
} else if (contentType.includes('application/text')) {
return response.text()
} else if (contentType.includes('text/html')) {
return response.text()
} else {
return response.text()
}
}
async function handleRequest() {
const init = {
body: JSON.stringify(body),
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
const response = await fetch(url, init)
const results = await gatherResponse(response)
return new Response(results, init)
}
addEventListener('fetch', (event) => {
return event.respondWith(handleRequest())
})
Run Code Online (Sandbox Code Playgroud)
我在https://tight-art-0743.ctohm.workers.dev/创建了一个工作人员,它基本上将您的 POST 请求的正文转发到公共请求箱。您可以检查它收到的内容:https://requestbin.com/r/en5k768mcp4x9/24tqhPJw86mt2WjKRMbmt75FMH9
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
let {method,headers}=request,
url=new URL(request.url)
// methods other than POST will return early
if(method!=='POST') return new Response(`Your request method was ${method}`);
const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/", request)
forwardRequest.headers.set('X-Custom-Header','hey!')
return fetch(forwardRequest)
}
Run Code Online (Sandbox Code Playgroud)
您可以看到它与一个简单的 CURL 请求一起工作
curl --location --request POST 'https://tight-art-0743.ctohm.workers.dev/' \
--header 'Content-Type: application/json' \
--data-raw '{"environment": {"name": "Sample Environment Name (required)"}}'
Run Code Online (Sandbox Code Playgroud)
在工人的代码中,有两件事值得注意:
init参数传递,通过该参数将原始标头和正文透明地转发到请求箱,如果需要,还允许进行一些额外的标头操作。另一个例子:让我们添加一条/csv路线。以 开头的请求/csv不会转发您的 POST 正文。相反,他们会下载远程 CSV 附件并将其 POST 到 requestbin。同样,我们并不是在等待实际的 CSV 内容。我们将响应正文的句柄传递给转发请求
async function handleRequest(request) {
let {method,headers}=request,
url=new URL(request.url)
if(method!=='POST') return new Response(`Your request method was ${method}`);
const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/",request)
if(url.pathname.includes('/csv')) {
const remoteSource=`https://cdn.wsform.com/wp-content/uploads/2018/09/country_full.csv`,
remoteResponse=await fetch(remoteSource)
return fetch(forwardRequest,{body:remoteResponse.body})
}
forwardRequest.headers.set('X-Custom-Header','hey!')
return fetch(forwardRequest)
}
Run Code Online (Sandbox Code Playgroud)
虽然您的代码理论上应该可以工作,但您解开响应的事实意味着您的工作线程可能会由于达到时间限制、CPU 或内存而中止。相反,当使用基于流的方法时,工作线程的执行一旦返回转发提取就会完成。即使传出 POST 仍在运行,也不受 CPU 或时间限制。