Fix AWS S3's 'XMLHttpRequest' Error on Trix - Rails 6

Published 07 April 2022

Cloud
Fix AWS S3's 'XMLHttpRequest' Error on Trix - Rails 6 Cover Image

I had this error on this very site and it was actually a pain. After digging around, I finally was able to resolve this and thought I could share the solution.

Just a bit of a backdrop, I am using Trix on parts of my App and AWS S3 for storage; trying to upload images was yielding the XMLHttpRequest error.
Upload error


To fix this error, navigate to the S3 dashboard and update your Cross-origin resource sharing (CORS) in JSON format. In your rules, you need to allow for PUT, POST, and DELETE requests from a specific origin (e.g. https://www.yourdomain.io) and allow for GET requests from all origins. 


[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "POST",
            "PUT",
            "DELETE"
        ],
        "AllowedOrigins": [
            "https://www.yourdomain.io"
        ]
    },
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "MaxAgeSeconds": 3000
    }
]

In the above configurations, we define the following properties:
  • - AllowedHeaders -  specifies which headers are allowed in a pre-flight OPTIONS request 
  • In our config, we use the * wildcard character which indicates that all headers are allowed in preflight requests. 
  • - AllowedMethods -  the set of methods enabled for this rule
  • - AllowedOrigins -  these are the domains allowed to make requests to the S3 bucket
  • - MaxAgeSeconds (optional) -  the time in seconds that your browser is to cache the preflight response for the specified resource

And there you have it, you should be all good. 

Tags:

aws, s3