Having trouble with CORS in your Angular application?

I am attempting to retrieve data from a site with the URL:

Using the $http service

After extensive research, I have come up with this CoffeeScript code snippet:

angular.module('blackmoonApp')
  .controller 'PricingCtrl', ($scope, $http) ->
    $http.defaults.useXDomain = true
    $http.get("https://bitcoinindex.es/api/v0.1/coinbase/usd/btc/last",
      headers:
        "Access-Control-Allow-Origin": "*"
    ).success (JSON) ->
      console.log JSON

The outcome is as follows:

"XMLHttpRequest cannot load https://www.bitstamp.net/api/ticker/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access."

I am uncertain if the website is intentionally blocking me (which seems unlikely given that it's an API), or if there are limitations with AngularJS when dealing with CORS.

Answer №1

Access-Control-Allow-Origin is a header that controls access permissions in responses.

The following code snippet:

  headers:
    "Access-Control-Allow-Origin": "*"

… actually sets a header for requests.

Remember to configure it on

https://www.bitstamp.net/api/ticker/
, rather than within your JavaScript code.

Allowing unrestricted JavaScript access to any server would pose a significant security risk.


I am uncertain if the website is blocking my access (although it's an API).

By default, all connections are blocked. You must explicitly authorize external JavaScript origins to gain access. Otherwise, anyone with a bitstamp account could be vulnerable to having their bitcoins stolen by simply visiting a website utilizing the API through their browser session and cookies.

Answer №2

Your code snippet shows an attempt to include the header Access-Control-Allow-Origin in a GET request using Angular's $http.

It's important to note that CORS (Cross-Origin Resource Sharing) requires the Access-Control-Allow-Origin header to be present in the response sent by the server, not in the initial request. Additionally, this header must match the exact domain of the page making the request.

Based on my tests, I found that:

  • https://bitcoinindex.es/api/v0.1/coinbase/usd/btc/last
    only allows CORS requests from its own domain, as indicated by the
    Access-Control-Allow-Origin:https://bitcoinindex.es
    response header.
  • https://www.bitstamp.net/api/ticker/
    did not have the Access-Control-Allow-Origin header at all.

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

Iterate over various selection lists and tally the frequency of each option being chosen

I am currently working on a website that requires multiple instances of the same select-option to be created. I want to keep track of how many times each option is selected, and save that count as a variable to be used in a PHP email function. For instanc ...

Tips for placing the header text at the center of a TemplateField in your design

I'm using a GridView with TemplateFields. I attempted to align the header text of the TemplateField to center by using HeaderStyle-HorizontalAlign="Center", but it doesn't seem to be working as expected. <asp:TemplateField HeaderTex ...

What is the best way to ensure that the input submit element is only visible after the input checkbox element has been checked?

For a school project, I am attempting to create a simulated reCAPTCHA box. Although my code is complete, I would like the functionality to submit your response from the input fields above only after selecting the reCAPTCHA checkbox. Upon researching, it ap ...

Jade Compilation with Gulp

Currently utilizing gulp-jade, I have encountered an error with a particular template: 557| 558| > 559| 560| .tabs-wrap(ng-show="eventExists"): .contain-center 561| 562| #room-tabs-contain.contain-disable.contain: .contain-center unexpec ...

Show that a CPU-intensive JavaScript function is executing (animated GIF spinners do not spin)

Displaying animated indicator or spinner gifs, then hiding them, is an effective way to communicate to the user that their action is being processed. This helps to assure the user that something is happening while they wait for the action to complete, espe ...

"Improve your Angular ngrx workflow by utilizing the sandbox pattern to steer clear of

Currently, I'm trying to determine whether my implementation of the ngrx and sandbox pattern is effective. Here's the issue I'm facing: getFiles(userId: number, companyId: number) { this.fileService.getFiles(userId, companyId).subscribe(re ...

Downloading a PDF file through the use of Ajax and TCPDF can be a straightforward process

I have encountered an issue with my code. It works perfectly fine when I run the PHP script without using AJAX as a GET request. When executing, I am prompted to download the rendered PDF and everything functions correctly. However, due to the necessity of ...

Error Encountered when Attempting to Retry AI SDK on Vercel's

I've been implementing code from the official AI SDK website but unfortunately, the code is not functioning properly. The error message I'm encountering is: RetryError [AI_RetryError]: Failed after 3 attempts. Last error: Failed to process error ...

What is the best way to patiently wait for lines to be printed out one by one

I am in the process of creating my own personal website with a terminal-style design, and I'm looking to showcase a welcome banner followed by a welcoming message. The effect I have in mind involves lines appearing individually from top to bottom and ...

"Utilizing jQuery to integrate an Ajax-powered Gauge using Google Visualization API

I need help creating a dynamic dashboard gauge that updates using ajax. The code snippet below shows what I have so far, but I'm struggling with updating the gauge itself. Any advice or suggestions on how to achieve this? google.load('v ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

Implementing RequireJS Singleton pattern with Web Workers

I'm currently working on a JavaScript project that utilizes the latest version of RequireJS. One of the modules I am defining is chessWorker, as shown below: var worker; define("chessWorker", ["jquery", "messageListener"], function($, listener) { ...

Real-time Broadcasts Straight to Your Web Browser

Feeling a bit frustrated with my current situation. I am eager to stream a live video broadcast to a web browser. At the moment, I am utilizing ffmpeg to stream a directshow live source as a webm stream to node.js, which then sends the stream to the http ...

Organizing content by title or link using jQuery

I am attempting to organize a list based on the title of a link so that it is displayed in an A-Z format. Unfortunately, I am unable to modify the HTML structure easily for better styling as I am restricted to using tr>tr>tr>. I am struggling to f ...

Obtain JSON data through an HTTP POST call

Here is a function that I have, which was mainly borrowed from the solution to another problem on SO: function sendPostRequest(url, data) { request( { url: url, method: "POST", json: true, body: data }, function(error, response, body) ...

When working with Next.js, I encountered a scenario where the useEffect() function was being triggered twice. I attempted to solve this issue by providing an empty array as the second argument, but to no

When working with Next-JS, I encountered an issue where the useEffect() function was running twice. While I heard that using an empty array as the second argument can fix this in React, it did not work in my case within Next-JS (which is based on React). ...

Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample d ...

Sharing a website link within Jquery and Ajax as a variable

Looking to dynamically load a collection of links on a page without writing out long statements for each one? Simply extract the URL from the attribute and pass it where needed. The code snippet below will demonstrate how to fetch the content using AJAX. ...

Tips for transferring a control's value between pages using AJAX in ASP.NET

How can I pass the value of a control, such as a textbox, from one page to another using AJAX in ASP.NET with C#? Any recommendations or advice would be greatly appreciated! ...

Uncover the underlying reasoning within the Vuex state

Struggling to find the right way to structure my Vuex store for a particular issue. In my store, I have an array of buttons or actions, totaling in the hundreds. Here's how they are currently organized: buttons: [ { text: 'Button 1', ...