я пишу рабочий инструмент cloudflare, но продолжаю получать ошибку cors, когда я отправляю что-то работнику из jquery / ajax
вот мой код jquery:
var settings = {
"url": "https://myworker.workers.dev/",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"first_name": $("#first_name").val(),
"last_name": $("#last_name").val(),
"email": $("#email").val(),
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Access to XMLHttpRequest at 'https://myworker.workers.dev/' from origin 'https://my.duda.co' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
.
следующий код показывает моего работника
addEventListener('fetch', event => {
if (event.request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(event.request))
} else {
event.respondWith(fetchAndApply(event.request));
}
})
function handleOptions(request) {
// Make sure the necesssary headers are present
// for this to be a valid pre-flight request
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
// If you want to check the requested method + headers
// you can do that here.
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
})
}
}
async function fetchAndApply(request) {
try {
const postData = await request.formData();
const url = new URL(request.url);
const result = fetchAndApplyPost(request, postData);
return result;
//console.log(result);
//const response = result;
//return new Response(`hello ${postData.get('email')}`)
} catch (err) {
return new Response(err);
}
}
async function fetchAndApplyPost(request, postData) {
let headers = {
'Content-Type': 'application/json'
}
const body = {
"properties": [
{
"property": "email",
"value": postData.get('email')
},
{
"property": "firstname",
"value": postData.get('first_name')
},
{
"property": "lastname",
"value": postData.get('last_name')
},
{
"property": "website",
"value": "https://www.clubtravoogle.com"
},
{
"property": "lifecyclestage",
"value": "customer"
}
]
};
const init = {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}
const response = await fetch('https://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/' + postData.get('email') + '?hapikey=d123123', init)
console.log('Got response', response)
return response
}