How can I set my http headers when using Ionic 6 with React?

I am using Ionic 6 with React, how can I set my http headers?

I tried doing it in the useIonViewWillEnter hook, did not work:

...
import { IonPage, useIonViewWillEnter } from "@ionic/react"
import { HTTP } from "@awesome-cordova-plugins/http"

....
const MyStuff: React.FC = () => {
  useIonViewWillEnter(() => {
    HTTP.setHeader(
      "*",
      "Content-Security-Policy",
      "frame-ancestors 'self' example.com"
    )
  })

What exactly are you trying to do? I’m pretty sure you want Content-Security-Policy to be set by your server, not Ionic.

I’m not familiar with the Cordova http plugin, but with the Capacitor HTTP plugin, you can do something like this:

  return Http.post({
    url: 'urlToPostTo',
    headers: {
      'Content-Type': 'application/json',
    },
    data: {
    },
  })

Where do you inject that code in an ionic project?

The HTTP plugin makes the HTTP request, so you want to use it wherever you make a network request (basically, the Capacitor HTTP plugin is similar to Axios and used in the same way).

If you have a lot of HTTP requests, a common approach is to wrap HTTP.post and HTTP.get in functions and then call those functions wherever you need to make a network request.

I think that’s what I am trying to do within the useIonViewWillEnter hook. As per the doc: " *ionViewWillEnter - Since ionViewWillEnter is called every time the view is navigated to (regardless if initialized or not), it’s a good method to load data from services."
Instead of loading data from services, which would be a network request, I am setting the header. Obviuosly not correctly.

ionViewWillEnter is called every time that component is loaded. There is no reason to set the header there because if you set the header and don’t make a network request, you’re running code (to set the header) for no reason.

Instead, you should wrap your http calls in a function that sets the header, as I described in my previous post.