Ways to resolve CORS issues for client-side requests with axios

I created a basic video player and I need to use various src files, none of which are stored on the same server as the application.

This is how the video code looks:

<video preload="metadata" @play="onPlay" @pause="onPause" :src="https://xxx.s3.amazonaws.com/sample_960x400.mp4">
</video>

When executing the above code, it functions without any CORS warnings.

However, when attempting a get request of the file using axios:

await axios.get('https://xxx.s3.amazonaws.com/sample_960x400.mp4', {
          withCredentials: false,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
            'Access-Control-Max-Age': 86400
          }
        })

This results in a CORS error:

Cross-Origin Request Blocked: The Same Origin Policy prevents reading the remote resource at . (Reason: CORS request did not succeed). Status code: (null).

I am utilizing Node.js with Express on the backend, but the files are not being served through my backend since they are hosted in the cloud.

My inquiries include:

  1. Why does no CORS error occur when the video tag retrieves the file?
  2. What causes a CORS error with axios?
  3. How can this be resolved?

Answer №1

The CORS policy, set by servers, dictates how resources can be accessed. The server hosting a video determines who can access it and in what manner. If you're unable to access the video with axios but can do so with the video tag, it indicates that the server allows the video to be loaded via browser HTML but not through the axios module.

If you have control over the videos displayed in your application, you could develop a feature to choose between using the video tag or loading with axios when posting. This way, you can verify if the video will display correctly before sharing it.

However, if your app automatically loads these videos, you may need to program the pages to hide inaccessible videos or display a message like "This video can't be loaded" along with its thumbnail instead of the video itself.

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

Listening for events with $rootScope.$on inside a service or factory

I'm encountering a peculiar issue with the $rootScope.$on method within a service or Factory. Here's an example of the service: app.service('testService', function($rootScope){ this.var1 = 5; this.change = function(n){ this.var1 ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Using Jcrop and Pixastic for Image Cropping

Currently, I am in the process of creating a website focused on image manipulation. I have been utilizing a lot of functions in Pixastic, which have proven to be quite effective. However, I have been contemplating if there is room for improvement specifica ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

Is there a way to alter visibility once a radio button has been selected?

I have a shape resembling a cube with 4 faces, all of which are currently visible. However, I would like to hide the other 3 faces when one face is showing. For example: I attempted setting the opacity of the other cube sides to 0 when the first radio but ...

Can we use an open-ended peer version dependency in package.json?

Question Summary Is it necessary for me to specify the peer dependency of @angular/core in my package.json file for a package containing easing functions that work with any version of Angular? "peerDependencies": { "@angular/core": "x.x" } Context I ...

Employ a variable within the fetch method to retrieve JSON data

Currently, I am in the process of developing a system that extracts specific information from a JSON file based on user input. One challenge that I am facing is how to incorporate a variable into the designated section of my code; fetch( ...

Having trouble displaying a group of threeJs renderers

I am working on a project that involves displaying multiple renderer, scene, and camera "groups" on a single HTML page. However, I encountered challenges when attempting to implement a render loop using requestAnimationFrame across all these groups. Despit ...

Close the spaces between the points in the cloud by increasing their size as you approach them

Something interesting happens when I view my point cloud from a distance - all the points seem to merge together, creating the optical illusion of a continuous surface. This is the effect I am aiming for. However, upon closer inspection, the individual poi ...

The jQuery change function appears to be functioning properly, but it is not producing any results

I am facing an issue with my jQuery code that rebuilds a dropdownlist based on the radio buttons selected. Although the code seems correct and the method works properly, the dropdownlist items do not update as expected. Can anyone provide some insight or i ...

What is the best way to utilize Gulp to build a Vue component tag within a JavaScript file?

I am trying to use Gulp to build a JavaScript file that is imported into Vue files. The desired code structure is as follows: export const myOrderTable = (h, _this) => { return [ { title: 'orderNo', align: 'center', ...

The Vue project is unable to locate the '@' symbol

After upgrading to vue-cli version 4.5.15, I encountered an issue where it couldn't resolve @ as ./src and all paths using '@' were not found. Can anyone explain why this is happening and suggest a possible solution? https://i.sstatic.net/P ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

I could use some assistance in creating arrays from a JSON file that contain identical keys

Here's the data in JSON format: [ { "id": 1, "picture": "image-hero-paramour.jpg", "title": "Project Paramour", "subheading": "Project made for an art museum near Southwest London. Project Paramour is a stateme ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

Combining text and hyperlinks within React/TypeScript variables for dynamic content

Seeking a way to combine a string and a link within an attribute of one variable: const News = [ { headline: 'some headline', text: "some text" + <a href='url'> click me </a>, }, ]; When I displa ...

What is the impact on resources when sending an AJAX request within a setTimeout() function?

I am in the process of developing a live chat system for my website, but I am uncertain about the best approach to take. Initially, I planned on using an AJAX request to retrieve the chat log at set intervals, which seems to be a common method based on var ...

How can I transform a collection of objects into an array using Javascript?

What would be the best way to convert this content into an array? https://i.sstatic.net/H6Fo9.png I have this: ...

In JavaScript, the act of shuffling an array will produce consistent results

I have created a random array generator by shuffling an initial array multiple times. SHUFFLE FUNCTION const shuffle =(array) => { let currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Ma ...

Error when utilizing the useLocation Hook: "The useLocation() function is only allowed within the scope of a <Router> component" in a React App

Developing a React application has led me to encounter an error while utilizing the useLocation hook from the react-router-dom library. The specific error message reads as follows: Error: useLocation() may be used only in the context of a component. In ...