Problem with CORS and ionic serve

Well, there is no way to handle the server side CORS issue at client side.

Well, daa… That WAS my point. And why is that? Why Native http can and angular/http can’t. Why can’t we get fix for that? There are MANY other people with the same problem and it’s very frustrating

That is because nothing other than providing the security to access resources from different origins.
Refer this link.

You have to be make sure that the resources you are providing access to it outside of your origin. But when you didn’t handle CORS from your server it doesn’t allow the browser to access your server resources.

And this and Cors handling work around might help to solve the issue from ionic native http.

Hi, you need to have the access control allow origin on the target device. Use the text/plain content type. It works good for me.
Following is the code in my target (arduino)

 HTTP.on("/status", HTTP_GET, []() {
            HTTP.sendHeader("Access-Control-Allow-Origin", "*");
            HTTP.send(200, "text/plain", "ok");
        });

in ionic i have the following headers:

let headers = new Headers();
    headers.append('Content-Type', 'text/plain');

My http post in ionic is below:

this.http.post(this.global.url, JSON.stringify(body), { headers: headers }).subscribe(data => { }, er

Yes, that is more or less what I am doing, but using xxx-form-urlencoded. The problem is this is a limited solution: you still can’t use other verbs like PUT or DELETE… for example, I would rather prefer to call DELETE /sessions/:id than POST /sessions/delete/:id.

Also, in my case, I do have control over the API server, and I have code there to allow any origin, any method, any headers… but still doesn’t work. I even install a Chrome extension to disable internal CORS checking, but problem continues.

I’ve thinking about this problem and I realized I haven’t been working logically about this. First thing I need to do is to check facts I am taking as granted, for example, that my API server is actually allowing any request. To do that, the best thing would be to create a small page in my apache server to send HTTP requests to the API server and check the response. So far I’ve being doing that using Insomnia, but most probably this app is sending its requests from file:// and not from http:// (being a hybrid app itself).

Another thing to do is to try to add logging messages to my API server to detect the moment a new request is received during the preflight phase. This way I will know for sure f the request is being blocked by my API server or the request is not even being received at all.

This way I can confirm two basic facts: the problem is or not being originated by my API server or my browser. If I can create a small web page that can send all kind of requests to my API server, then I will be sure the problem is being generated by the ionic web server.

try to use ionic cordova plugin HTTP native

Yes, but the problem with CORS is caused by the origin. When running from the device, request have a file:// origin (so CORS doesn’t apply), while when running on ionic serve they have a http:// origin.

Well, it turned out I was the one messing up things. My API server CORS configuration was off and that was the cause of the CORS errors at my ionic app. If anyone lands here looking to solve this same problem, this is the code you need to put in your Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("corsAllowAllPolicy",
        builder =>
        {
            // IMPORTANT:
            // Wildcard origins and allowAnyCredentials CAN NOT be used
            // together and will prevent CORS policy to apply.
            builder.WithOrigins("http://*:*")
                   .allowAnyMethod()
                   .allowAnyHeaders();
        });
    });

    // IMPORTANT
    // CORS policy must be defined BEFORE calling AddMvc() middleware.
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // Your other code goes here.
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors("corsAllowAllPolicy");
    app.UseMvc();
}

Now my app works perfectly on the browser, buy in muy device the requests to the API server are failing with an unknown error - status: 0… but that is another issue altogether :slight_smile:

Thanks all for your help on this.

Why has no one suggested running chrome with security disabled for development purposes?

This error is only happening locally and won’t happen when he’s running from app to backend on the device.

Solution (if you’re on mac):

1. Quit Chrome
2. Run this at the terminal: 
open -a Google\ Chrome --args --disable-web-security --user-data-dir

Sorry I don’t know the windows command equivalent.

FYI, here’s my Startup.cs file in my .NET core project that works fine with CORS:

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

            app.UseMvc();
        }

@rdsethi we’re running into that issue too - have you tried any work-arounds?

[yashwanth493] actually suggested that and I tried it with no effect. About .NET core, I tried different configurations without success. My problem was ASSUMING that the CORS configuration was ok when, in fact, it was not. Was not until I created a sample html page to test the CORS problem that I found out the problem was being caused by my api server.

Had you tried the solutions mentioned in this post?

Sounds like the Chrome fix is now being rolled out.

Try using UIWebView.

“UIWebView never enforced CORS, but WKWebView does.” - https://ionicframework.com/docs/v3/wkwebview/.

IOs now demands using WEBview . You cannot rollback and say CORs is fixed