Ionic is being hindered by the CORS policy, specifically due to the absence of an 'Access-Control-Allow-Origin' directive

I have developed an Ionic application that connects to an API website. To safeguard my website, I integrated CloudFlare for added protection. Prior to activating the Under Attack Mode, the requests were being successfully sent without any errors. However, after enabling this mode, an error is now displayed in the console:


Access to XMLHttpRequest at 'https://mywebsite.org/api/mobile/news?pageSize=15&currentPage=1&language=undefined' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The backend of the app is a Flask microservice and I have configured the CORS settings as follows:

cors.init_app(app, resources={r"https://mywebsite.org/api/*": {"origins": "https://mywebsite.org"}})

Whenever a get request is sent from the application, I include Access-Control-Allow-Origin in the headers:

let headers = new HttpHeaders({
    "Access-Control-Allow-Origin":"https://mywebsite.org/",
    "origin":"https://mywebsite.org/"
});

@Injectable({
    providedIn: 'root'
})
export class DataApiService {

    private apiUrl: string = 'https://mywebsite.org/api';


    constructor(
    private http: HttpClient,
    private translate: TranslateService
    ) { }

    // Get news
    apiRequest(url: string, params?:any){

    const apiUri = `${this.apiUrl+url}`;

    if(params){
        params.language = this.translate.getDefaultLang();
    }

    return this.http.get(apiUri, { headers: headers, params: params }).pipe(
        delay(
        500
        ),
        map(
        (res:any) => {
            return res
        }
        )
    )
    }
}

If anyone could provide assistance, it would be greatly appreciated.

Answer №1

check out this resource

https://ionicframework.com/docs/troubleshooting/cors

make sure to use the host "test.test.co" instead of localhost (when using 'ionic serve --host test.test.co')

next, navigate to your local disk

locate C:\Windows\System32\drivers\etc

edit your hosts file accordingly

127.0.0.1 test.test.co

apologies for any language mistakes

I trust this information was beneficial

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to invoke a function in a functional React component from a different functional React component?

I need to access the showDrawer method of one functional component in another, which acts as a wrapper. What are some best practices for achieving this? Any suggestions or insights would be appreciated! const TopSide = () => { const [visible, se ...

Tips on sending data to an Angular ng-bootstrap modal for data binding

Scenario: ChildComponent - with numerous ngModel binding elements. <input [(ngModel)]="TryToPassDataModel.name">; ParentComponent - btn.onClick = function() { this.bsModalRef = this.modalService.open(ChildComponent, TryToPassData ...

Using Angular 5 to showcase multiple charts with Chart.js, each chart appearing on its own tab

I have successfully displayed a single chart, but I am facing an issue while trying to display that chart for each tab of a mat-tab-group with different data on each tab. The chart is a part of a larger dashboard consisting of multiple charts, and I have i ...

Creating a variety of active button colors using Bootstrap and Angular's ngFor

Is there a way to assign individual colors to each button in a menu with four buttons? I want different colors for the active state and rollover effect of each button. https://i.sstatic.net/3rW0L.png .html <div class="d-flex justify-content-center"&g ...

What could be causing forkJoin to malfunction with observers?

I attempted to simulate server requests by creating two BehaviorSubjects for blocks and fields. const _blocks$ = new BehaviorSubject<any[]>([]); const _fields$ = new BehaviorSubject<any[]>([]); Next, I set up two observers: of(true) . ...

Optimal Angular Project Structure for Creating an App with Admin Backend

After finishing "ng-book: The complete book on Angular 6," I am diving into Angular as a newcomer. As I venture into building my application, I have a specific question that has been lingering in my mind. The vision for my project includes: MainLayout: ...

Unresolved peer dependency issue in NPM recursion

I'm attempting to enhance my @ionic-native/core in order to facilitate the installation of an OIDC client. Regardless of the commands I've attempted, I consistently encounter an error: UNMET PEER DEPENDENCY @ionic-native/[email protected] ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

Choosing Angular.json setups while executing a Docker multi-stage construction

I am currently in the process of developing an Angular6 application with a Docker multistage build. The default angular.json file generated by angular.cli includes a build section containing various configurations. To choose a specific configuration, I can ...

GraphQL type featuring a union property defined inline

Trying to create a matching GQL type for this Typescript interface: interface List { items: [String] | [[String]] } Initially, I attempted to keep it straightforward: type List { items: [String]! | [[String]!]! } However, GQL did not approve of tha ...

The concept of Border-Merging within Material Design Tables

Is there a way to implement the following border style in a Material Design Table: border-collapse: collapse; I tried adding a border to .mat-cell: .mat-cell { border: 1px solid; } However, in some instances, the border appears to be 2px. The reas ...

What is the most efficient method for transforming files using a heroku deployed application?

I'm currently developing a Discord bot deployed on Heroku that has a function to convert video files to .mp4 format and then embed the file in a reply message. When running the function locally, everything works fine. However, when running it on the d ...

What is the reason behind TypeScript not narrowing types with control flow and never in the case of arrow functions?

Why does Typescript fail to narrow with a call to fail, but will narrow with a call to fail2? Is this a bug in Typescript? const fail = (message?: string): never => { throw new Error(message); }; function fail2(message?: string): never { throw ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

Can Angular support nesting forms up to two levels deep?

In my Angular project, I am faced with the challenge of nesting a formgroup two levels deep to achieve a specific functionality. Here is the scenario: I have several small formgroups all belonging to a common parentform. However, for a new page, I need to ...

Is it possible to establish a default or recommend a specific folder arrangement when conducting a direct download without the need for a zip file?

Q: Can a custom folder structure be recommended for direct downloads without using a zip file? My AngularJS application generates text files that need to be imported into a specific folder structure on a commercial machine. Is there a way to prompt users ...

Using Typescript to create an interface that extends another interface and includes nested properties

Here is an example of an interface I am working with: export interface Module { name: string; data: any; structure: { icon: string; label: string; ... } } I am looking to extend this interface by adding new properties to the 'str ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Refreshing Angular 9 component elements when data is updated

Currently, I am working with Angular 9 and facing an issue where the data of a menu item does not dynamically change when a user logs in. The problem arises because the menu loads along with the home page initially, causing the changes in data to not be re ...

What is the best way to change the user profile type?

According to the meteor-typescript's definition file, the user.profile is typed as any. Is there a Typescript method to extend the user object and modify the profile type? I attempted the following: interface IMyUserProfile { foo: boolean; } nam ...