Ed
Explore posts from serversCDCloudflare Developers
•Created by Ed on 5/28/2024 in #workers-help
Submit form to Worker to store in R2
I've have been dealing with this for hours now and I'm so sick of this
Worker code
Literally copy and pasted from the docs as what I wrote would not work, but this doesn't work either.
My Form Code
export default {
async fetch(request, env) {
const url = new URL(request.url);
const key = url.pathname.slice(1);
switch (request.method) {
case 'PUT':
await env.R2.put(key, request.body);
return new Response(`Put ${key} successfully!`);
case 'GET':
const object = await env.R2.get(key);
if (object === null) {
return new Response('Object Not Found', { status: 404 });
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('etag', object.httpEtag);
return new Response(object.body, {
headers,
});
case 'DELETE':
await env.MY_BUCKET.delete(key);
return new Response('Deleted!');
default:
return new Response('Method Not Allowed', {
status: 405,
headers: {
Allow: 'PUT, GET, DELETE',
},
});
}
},
};
export default {
async fetch(request, env) {
const url = new URL(request.url);
const key = url.pathname.slice(1);
switch (request.method) {
case 'PUT':
await env.R2.put(key, request.body);
return new Response(`Put ${key} successfully!`);
case 'GET':
const object = await env.R2.get(key);
if (object === null) {
return new Response('Object Not Found', { status: 404 });
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('etag', object.httpEtag);
return new Response(object.body, {
headers,
});
case 'DELETE':
await env.MY_BUCKET.delete(key);
return new Response('Deleted!');
default:
return new Response('Method Not Allowed', {
status: 405,
headers: {
Allow: 'PUT, GET, DELETE',
},
});
}
},
};
const form = document.getElementById('reComments')
form.addEventListener('submit', (e)=>{
e.preventDefault();
onSubmit(form);
});
function onSubmit(form){
const formData = new FormData(form);
fetch('https://URL-HERE.workers.dev', {
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error));
console.log(`This is the data from the website being sent to cloudflare:`, formData);
};
const form = document.getElementById('reComments')
form.addEventListener('submit', (e)=>{
e.preventDefault();
onSubmit(form);
});
function onSubmit(form){
const formData = new FormData(form);
fetch('https://URL-HERE.workers.dev', {
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error));
console.log(`This is the data from the website being sent to cloudflare:`, formData);
};
2 replies