Hank Anzis
Hank Anzis

Reputation: 91

Local axios call cannot connect to local .net core API

I am trying to test some performance issues on a .net core API (VS2019 .net core 2.2)

I can run the API on my local machine using swagger.

The API is called from a ReactJS web app using axios calls which I am running locally. Calling the API located on the Azure servers (dev, test, prod) is successful.

When I call the local API from the web app, the API receives the request and returns a response but it is not received from in the web app. I get this error

Error: Network Error at createError (http://localhost:3000/static/js/0.chunk.js:149705:15) at XMLHttpRequest.handleError (http://localhost:3000/static/js/0.chunk.js:149256:14) {config: {…}, request: XMLHttpRequest, response: undefined, stack: 'Error: Network Error at createError (http…ocalhost:3000/static/js/0.chunk.js:149256:14)', message: 'Network Error'}

I saw on similar posts that this could be a CORS issue. The API sets up CORS as

app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

Does anybody have any idea I can try to identify why I cannot connect the web app to the api locally?

Thanks in advance Hank

Upvotes: 0

Views: 828

Answers (1)

Rena
Rena

Reputation: 36715

Specifying AllowAnyOrigin and AllowCredentials is an insecure configuration and can result in cross-site request forgery. The CORS service returns an invalid CORS response when an app is configured with both methods.

You could change AllowAnyOrigin to WithOrigins("Specify the send request origin").

app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod()
                            .WithOrigins("Specify the send request origin").AllowCredentials());

Or you could change AllowAnyOrigin to .SetIsOriginAllowed(_ => true):

app.UseCors(policy => policy.AllowAnyHeader().AllowAnyMethod()
                            .SetIsOriginAllowed(_ => true).AllowCredentials());

Upvotes: 1

Related Questions