Search code examples
google-app-enginegoogle-cloud-platformhttp-headersresponse-headershapi

HapiJs + Google Cloud Storage not sending No 'Access-Control-Allow-Origin' header is present on the requested resource


I have deployed a HapiJs api to Google App Engine, which has two simple GET endpoints to retrieve .pdf files from, and a POST endpoint to store .pdf in a bucket. I am relatively new to GCS, so I am sure I am doing something wrong here.

I keep receiving the following error when I call either GET endpoint:

Access to XMLHttpRequest at 'https://my-production-url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

the response header, surprise surprise... doesn't have a 'Access-Control-Allow-Origin': * header.

Now, this is my configuration:

// index.ts

bucket.setCorsConfiguration([{
    "origin": ["*"],
    "method": ["GET", "POST"],
    "responseHeader": ["Access-Control-Allow-Origin"],
    "maxAgeSeconds": 360,
  }])

...

const server: hapi.Server = new hapi.Server({
    port: 8080,
    host: 'localhost',
    routes: {
        cors: true, // also tried { cors: { origin: "ignore" } } and { cors: { origin: ["*"] } }
    }
});

...

server.route({
    method: 'GET',
    path: '/all-project-waivers/{id}',
    handler: async (request: hapi.Request, h: hapi.ResponseToolkit) => {
        try {
            // amazing stuff here
            return h.response(files).header('Access-Control-Allow-Origin', '*').code(200);
        ... more amazing stuff below

I have tried all sorts of things, but I don't seem to be able to have the header shipped to the client.

To my knowledge, the api is in charge of attaching the header to the response, has anybody had the same problem?

Thank you in advance


Solution

  • after hours of trial and error, I managed to fix it by simply setting the host to

    0.0.0.0
    

    instead of ...

    localhost
    

    hopefully this will spare someone hours of self harm in the future