How to make cross-domain HTTP GET requests with Angular 2

I am attempting to retrieve a JSON file from a remote server. Here is the module I have written :

import { Component }               from '@angular/core';
import { Injectable }              from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable }              from 'rxjs/Observable';

import './rxjs-operators';


@Component({
    selector: 'map',
    templateUrl: 'map/map.component.html'
})

@Injectable()
export class MapComponent{

    private properties;

    constructor(private http: Http){

        this.properties = null;
    }

    ngOnInit(){

        this.getPropertiesInTheArea();
    }

    getPropertiesInTheArea(){

        let url = "https://raw.githubusercontent.com/sdeering/50-jquery-function-demos/cd89f8592b96d0a79c10aa64fa43c1bf01312643/data/data.json";

        this.http.get(url)
                .map(response => response.json())
                .subscribe(
                    data => this.properties = data,
                    err => console.error(err),
                    () => console.log("Fetched Properties\n\n" + JSON.stringify(this.properties))
                );
    }

}

This module works well with fetching a local JSON file :

let url = "http://localhost:3000/map/data.json";

However, when attempting to fetch a remote resource (such as raw.githubusercontent.com), I encounter the following error in the console:

"EXCEPTION: [Exception... "" nsresult: "0x805e0006 ()" location: "JS frame :: http://localhost:3000/node_modules/zone.js/dist/zone.js :: scheduleTask :: line 1241" data: no]"

Unhandled Promise rejection: Exception { message: "", result: 2153644038, name: "", filename: "http://localhost:3000/node_modules/…", lineNumber: 1241, columnNumber: 0, data: null, stack: "scheduleTask@http://localhost:3000/…" } ; Zone: ; Task: Promise.then ; Value: Exception { message: "", result: 2153644038, name: "", filename: "http://localhost:3000/node_modules/…", lineNumber: 1241, columnNumber: 0, data: null, stack: "scheduleTask@http://localhost:3000/…" } undefined

Thank you for any assistance provided.

Answer №1

Looks like this may be Angular2.

If you're experiencing difficulties fetching data, it could be a CORS problem. Take a look at the network tab in your developer tools to troubleshoot.

Fetching data from a different server may not work unless that server supports JSONP or has the proper access-control headers set. It's possible that everything is functioning properly when running locally because the app is served from localhost.

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

Leveraging current state data (from store) in ReactJS promptly

Working in React with Flux and faced with a challenge. Within my component, I have a function triggered by a click event: onClickEventEdit: function(itemId) { ScheduleActions.getEventById(itemId) // sets the retrieved data into `currentEventById ...

Using CKEditor5 to Capture and Edit Key Presses

I'm currently working on capturing input from a CKEditor5 within an Angular application using TypeScript. While I am able to successfully display the CKEditor and confirm its presence through logging, I am facing difficulties in capturing the actual i ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

Error in jQuery when element is not found

On my website, I use multiple jQuery functions, but not all of them are necessary on every page. These functions are all located in one XXX.js file, such as: jQuery(function() { $(".title").slug({ slug:'slug', hide: false }); }); ...

I'm encountering an issue when attempting to send a parameter to a function within a typescript code

Recently, I started using Typescript and encountered an issue with passing arguments to a function in Typescript. This particular function is triggered when rendering a form modal. However, I keep receiving two errors: "Argument of type 'Promise& ...

Experience the seamless integration of FullCalendar with Angular 5 for a dynamic and

Looking for assistance in integrating fullcalendar with Angular 5 seamlessly? Trying to implement it into a specific component and have already installed necessary packages: jquery moment fullcalendar fullcalendar-scheduler Referencing this post on Stack ...

Can a file be successfully retrieved using an HTTP POST request?

Can a file be downloaded using HTTP POST method? I am aware of the "Get" method (windows.location), but in my scenario, there are many parameters that need to be sent to the server. ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

The functionality of Angular material seems to be malfunctioning within an Angular library

After observing the potential for reusable code in my Angular projects, I decided to create a common library to streamline development. Following the steps outlined in an article (link: https://angular.io/guide/creating-libraries), I successfully created t ...

The error "Prop does not exist on type 'PropsWithChildren'" occurs when attempting to dispatch an action with react-redux

When attempting to dispatch the action, I am encountering this error: The error message reads: Property 'fetch_feed_loc' does not exist on type 'PropsWithChildren<{ onSubmitForm: any; }>'. Another error states: Property &apos ...

Issue with angular 8 radio button not being selected

Here is the HTML code I am working with: <div *ngFor="let option of systemEquipmentGroup"> <h5>{{option.optionGroupName}}</h5> <div> <label style="display: block;" * ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Trouble with passing AJAX calls from JavaScript object to PHP

I've encountered an issue while trying to extract information from a form and send it via AJAX to a PHP file for storing in a CSV file. Surprisingly, the PHP file is receiving the JavaScript object with empty fields even though they appear filled in t ...

"Exploring the New Feature of Angular 17: Named Router Outlets Implemented

One issue I am facing with my application is the rendering of different pages based on whether a user is logged in or not. The generic pages like the landing or logout page should be displayed within the primary router-outlet when the user is not logged in ...

Utilize a singular ajax function to handle various events with personalized data parameters

Could someone help me with this specific issue? Here is an explanation. Let's say I have a function called load_window() and various events like clicks, changes, etc. How can I properly create a custom_data variable in these events and use it in the ...

The content in an app using Ionic and Angular is being obstructed by the bottom tabs, preventing users

I am facing an issue with my Ionic and Angular app. When I place tabs at the bottom of my page, outside the ion-content, the scrolling stops working inside the ion-content and the fab button, which is located inside the ion-content, ends up covering the ta ...

The datetimepicker feature is designed to function only in rows that are positioned above the row that was previously selected in

Hello everyone, I am new to database projects and this is my first one. Please forgive any basic mistakes I make. Currently, I am working on a Multi-Update Form where I encounter an issue. When I select a row and choose a date using the datetimepicker in ...

There seems to be an issue with Material-UI and TypeScript where a parameter of type 'string' does not have an index signature in the type 'ClassNameMap<"container" | "navBar" | "section0">'

My current project is encountering a TS Error stating "(No index signature with a parameter of type 'string' was found on type 'ClassNameMap<"container" | "navBar" | "section0">'.)" The code below is used to assign styles to vari ...

Initiate loading process upon page load, rather than triggering it upon a click event, utilizing ajax and PHP mechanisms

$(document).ready(function(){ $('button.load-html').click(function(){ $('#content-container').load('http://example.com/data.php?param=12345'); return false; }); }); Click here to trigger t ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...