Another problem with CORS again?

My rails application uses the host http://myhost.dev to search for music through the vk.com API. The API provides a search method called audio.search. Below is the code snippet from my search.js.erb file which is executed via a remote link to the search action of a controller:

VK.api('audio.search',{q: "<%= j params[:query] %>", auto_complete: "1", sort: "2", count: "200"},function(data){
  if(data.response) {
    $(function() {
      var audio = $('audio');
      var a = audiojs.create(audio);
      var first = $('ol a').attr('data-src');

      console.log(first);
      $(".song-title").text($('ol a').first().text());
      $('ol li').first().addClass('playing');

      audio.load(first);
    });
  }

  else {
    /* handle error */
  }
});

The application.js file initializes the vk application as follows:

  VK.init({
    apiId: '3650724'
  });

Everything works fine except on a different route, for example, http://myhost.dev/foo. On this route, there is another audio tag and the code looks like this:

:javascript
  var artist = '#{ @artist.name }';

  var track_name = $('ol a').first().attr('data-src');
  VK.api('audio.search',{q: artist + " - " + track_name, auto_complete: "1", sort: "0", count: "1"},function(data){
    if(data.response) {
      $(function() { 
        alert("lol");
        var audio = $('audio');
        var a = audiojs.create(audio);
        var first_track = data.response[1];
        $(".song-title").text(first_track.title);
        $('ol li').first().addClass('playing');

        console.log(first_track.url);
        audio.load(first_track.url);
      });
    }
    else {
      alert("fail!");
    }
  });

Although the response is valid JSON, I encounter an error when loading the resource URL to the player:

XMLHttpRequest cannot load http://cs4967.vk.me/u5366455/audios/some.mp3. Origin http://myhost.dev is not allowed by Access-Control-Allow-Origin.

Answer №1

The issue does not lie with your API requests, but rather with the <audio /> element (and <video /> as well) which only allows requests to be made from the same domain.

VK did not provide CORS headers for the URL mentioned, even though it is a 404 error. In this scenario, you may need to set up a proxy on your own server to fetch the mp3s and then stream them from there.

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

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

What steps can be taken to prevent the "unable to convert undefined to an object" error from occurring?

There seems to be an issue with some of the documents not containing the planDetails and planId properties, resulting in the error "can't convert undefined to an object." However, I need to fetch that document whether these properties exist or not. Ho ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

The supported browser is unable to import ES6 modules

Attempting to incorporate moment.js as an es6 module. The most recent version of Chrome is being utilized. Referring to the conversation here, I experimented with the src path (es6) import * as moment from './node_modules/moment/src/moment' A ...

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

Is there a way to design a catalog page for my website that doesn't include a shopping cart or detailed product pages?

I am looking to create a catalogue feature similar to Newegg's for my website, but with a simplified approach. I have never attempted something this advanced before and I am wondering if it is possible to achieve. My plan is to use PHP and JS for the ...

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

Attempting to sort through elements in JavaScript

I'm looking to filter specific films based on choices made in the dropdown menus below. <select id="filmDropdown"> <option value="0">All Films</option> <option value="1">Film 1</option> <option ...

Error thrown: Upon attempting to reopen the modalbox after closing it, an uncaught TypeError is encountered, indicating that the function $(...).load

An unexpected error occurred: $(...).load(...).modal is not functioning properly After closing a modal, I encountered this error in the console when attempting to reopen it. Strangely, it seems to work intermittently for a few times before throwing this e ...

Is there a way to verify the content of a span and automatically guide the user elsewhere if it meets certain criteria?

Currently, I am facing an issue with adding Google authentication to my website as the redirect function is not working properly. As a solution, I plan to implement manual redirection using JavaScript in case the value of the span element is <span id= ...

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...

Tips for smoothly transitioning between tabs in IONIC by simply clicking on a link or url

Imagine having two tabs within my application: tab-one and tab-two. I am trying to navigate from the view of tab-one (one.html) to the view of tab-two (two.html). I have attempted using $state.go(), $location, and $window.location but none of them seem t ...

Which data type should I utilize to transfer an array of integers using ajax?

[HttpDelete] public JsonResult ReservationCancel(int[] reservationId) { var model = ReservationDAO.getReservation(reservationId); return Json(model,JsonRequestBehavior.AllowGet); } I have a list of Ids (1, 2, 3, 4, 5, 6, 7) that I want to delete a ...

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the ...

Async/await is restricted when utilizing serverActions within the Client component in next.js

Attempting to implement an infinite scroll feature in next.js, I am working on invoking my serverAction to load more data by using async/await to handle the API call and retrieve the response. Encountering an issue: "async/await is not yet supported ...