Hello, I am new to using workers. I wanted to make a demo function for myself and have tripped up sending a response back to the client. Im not sure if its a worker issue or client side error.
The worker receives 2 numbers and returns the sum. everything seems to work on the worker side
addEventListener('fetch', event => {
if(event.request.method === 'POST'){
event.respondWith(handleRequest(event.request))
}
})
/**
* Respond to the request
* @param {Request} request
*/
const addNumbers = (first, second) => {
const total = first + second;
return total;
}
async function handleRequest(request) {
const { numOne, numTwo } = await request.json();
const data = {
total: addNumbers(numOne, numTwo)
}
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response( JSON.stringify(data), init)
}
This returns
200 OK
content-length:
11
content-type:
application/json;charset=UTF-8
{"total":3}
On my client side
document.getElementById("form").addEventListener("submit", function (event) {
const numOne = document.getElementById("num-one").value;
const numTwo = document.getElementById("num-two").value;
const data = {
numOne,
numTwo,
};
fetch("https://xxxxxxxxx.xxxx.workers.dev/", {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then(function (response) {
console.log(response);
});
event.preventDefault();
});
I log this
What am I doing wrong?