Search code examples
reactjsaxios

React - Axios Call ERR_CONNECTION_REFUSED


I'm training on React to assess the work to replace our front end from ExtJS to React. I downloaded a free React template, and managed to set up the login but when I try to make a simple get axios call to my API I get the error 'ERR_CONNECTION_REFUSED'.

I tried with our current front and the call is working, I tried as well in Postman and it's working.

const [products, setProducts] = useState([]);
const { getAccessTokenSilently } = useAuth0();

useEffect(() => {
    const fetchProducts = async () => {
        try {
            const accessToken = await getAccessTokenSilently();
            const response = await axios.get('http://localhost:10000/******/Currencies', {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            setProducts(response.data.data);
        } catch (error) {
            console.error(error);
        }
    };

    fetchProducts();
}, [getAccessTokenSilently]);

EDIT :

Code snippet from postman :

const axios = require("axios");

let config = {
  method: "get",
  maxBodyLength: Infinity,
  url: "localhost:10000****/Currencies",
  headers: { Authorization: "Bearer eyJhbGciOiJS...." },
};
axios
  .request(config)
  .then((response) => {
    console.log(JSON.stringify(response.data));
  })
  .catch((error) => {
    console.log(error);
  });

While investigating, I noticed our current front end uses a node js server. After starting it, I now have a CORS error.

Here's the startup class of the Web API which is in .Net framework 4.8 :

    public void Configuration(IAppBuilder app)
    {
        app.UseCors(new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context =>
                    Task.FromResult(new CorsPolicy
                    {
                        AllowAnyMethod = true,
                        AllowAnyHeader = true,
                        Origins = { "http://localhost:10000", "http://localhost:3000" }, // Specify allowed origins
                        SupportsCredentials = true // Enables credentials for cross-origin requests
                    })
            }
        });

        app.Use(async (context, next) =>
        {
            if (context.Request.Method == "OPTIONS")
            {
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync("");
            }
            else
            {
                await next();
            }
        });

        var authorizedIPs = new HashSet<string> { "::1" }; //::1 = localhost
        foreach (var ip in Config.RestrictedAccesIps)
        {
            authorizedIPs.Add(ip);
        }
        app.Use(typeof(IpFilterMiddleware), authorizedIPs);

        if (Config.AuthMode == WebApi.GlobalConst.Auth0)
        {
            if (string.IsNullOrEmpty(Config.OrganizationId))
            {
                throw new ArgumentNullException("Organization Id missing");
            }

            var domain = Config.Domain;
            var apiIdentifier = Config.ApiIdentifier;
            var keyResolver = new OpenIdConnectSigningKeyResolver(domain);

            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidAudience = apiIdentifier,
                        ValidateIssuer = true,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime = true,
                        ValidateAudience = true,
                        ValidIssuer = domain,
                        IssuerSigningKeyResolver = (token, securityToken, kid, parameters) => keyResolver.GetSigningKey(kid)
                    }
                });
        }

        // Configure the routes and add filters
        var httpConfiguration = WebApiConfig.ConfigureWebApi();

        // Use the extension method provided by the WebApi.Owin library:
        app.UseWebApi(httpConfiguration);
    }

The error I now have is the preflight option call that get rejected with a Http 401 error.


Solution

  • My issue was the proxy, I had to put :

    proxy: 'https://localhost:3000'

    In the package.json