I’m trying to do a typescript fetch and got some troubles with CORS.
- FROM http://localhost:3000 (solidjs web app)
- THROUGH https://localhost:6331 (Ocelot gateway)
- TO http://localhost:1339 (asp.net webapi)
Although I set up the CORS (with ‘Access-Control-Allow-Origin’) in my webapi project, I have the error
Access to fetch at ‘https://localhost:6331/what/ever’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
WEB API:
app.MapMethods("/api/v1/what/ever", new[] { "OPTIONS" }, (HttpContext context) =>
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:3000");
context.Response.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, POST");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
context.Response.Headers.Add("Access-Control-Max-Age", "86400");
return Results.Ok();
});
Gateway
{
"GlobalConfiguration": {
"BaseUrl": "https://localhost:6331"
},
"Routes": [
{
"DownstreamPathTemplate": "/api/v1/what/ever",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "host.docker.internal",
"Port": "1339"
}
],
"UpstreamPathTemplate": "/what/ever",
"UpstreamHttpMethod": [ "POST", "OPTIONS" ]
}
]
}
SolidJs Web App
const response = await fetch("https://localhost:6331/what/ever", {
method: 'POST',
cache: "no-cache",
body: JSON.stringify(dataToSubmit),
headers: {
'Content-Type': 'application/json'
},
});
The request arrives at the webapi and is executed there, but there is no response returned. Does anyone know what the problem could be?
2
Answers
Seems like everything was ok, except the gateway CORS:
and
I used your code on a similar configuration, without docker.
Using your
app.MapMethods
it does not work.But it does when i add POST in addition to "OPTIONS" (used by preflight request) lke this:
You should try this at first.
Furthermore, i added 2 headers, with some information about the request headers and the path, to check what is really sent to the webapi: that information is returned even when you have a failing preflight.
To force the fail, you can set 3001 as port value in webapi map method.
With port 3000 in webapi checked that works if i call the webapi directly from the browser
localhost:3000
, or if i call ocelot -> webapi (changing the ports an paths, naturally).For this purpose a used your simple vanilla js fetch.
Both was running in my machine, i don’t know if you are using running container with compose or something else.
However i thing this should work for you.
Hope it helps!
Cose belle!