Fetch and fetchProps - adding headers to prevent CORS
Closed this issue · 6 comments
I have a cloudfare worker that I access as my App API. When using fetch in Svelecte, it has a CORS issue. I need to add headers but the example to use fetchProps is a bit confusing and I can't get it to work.
My SVelecte works fine with a local json file and the API is accessible via the url in a browser.
My Selecte is setup like this:
<Svelecte
bind:this={svelecte}
inputId="drugs"
name="drugSelection"
multiple
bind:value={selectedItems}
valueField="name"
labelField="name"
placeholder="Select Drugs to Add"
clearable
closeAfterSelect={true}
collapseSelection="blur"
valueAsObject={true}
strictMode={false}
fetch="https://vet-drugs.vetcalculators.workers.dev"
fetchProps={fetchProps}
on:change={handlekg}>
</Svelecte>
script Copied from here (migration-guide)
const fetchProps = {
headers: {
Content-Type: "application/json;charset=UTF-8",
Access-Control-Allow-Origin: "*",
Cache-Control: "public, max-age=2000, s-maxage=2000"
}
}
The fetchProps
are options of (Fetch Request)[https://developer.mozilla.org/en-US/docs/Web/API/Request/Request] object.
For CORS to work, your Cloudflare worker must return Access-Control-Allow-Origin: * | <allowed-origin>
header and probably other Access-Control-*
headers.
const fetchProps = { ... }
Basically you specified valid CORS response headers to fetch request. fetchProps
are good for specifying custom headers and some other request-related settings.
Thanks for responding.
My cloudfare worker is configured with these headers
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=1000, s-maxage=1000"
}
using curl -I https://vet-drugs.vetcalculators.workers.dev shows a valid response but using it in Svelecte like this,
fetch="https://vet-drugs.vetcalculators.workers.dev"
or with
const fetchProps = {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=1000, s-maxage=1000"
}
};
fails due to access control checks.
It's driving me crazy!!
You didn't get what I meant: here is your solution REPL. You're welcome 😊
Thanks! I used that initially and it failed as I described, but I eventually found that I needed to add this additional header to my cloudfare worker to get it to work.
"Access-Control-Allow-Headers": "Content-Type, X-Requested-With",
Again, I really appreciate your help and response!
Mike
Glad you solved it! Sorry for the inconvenience with default x-requested-with
header.
WHen thinking about...Probably will be the best to do not set any headers by default and/or allow globally configurable fetchProps
.