The request to search for "aq" on localhost at port 8100 using Ionic 2 resulted in a 404 error, indicating that the

Trying to create a basic app that utilizes an http request, but facing challenges with cors in ionic 2.

To begin with, modifications were made to the ionic.config.json

{
  "name": "weatherapp",
  "app_id": "",
  "v2": true,
  "typescript": true,
   "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://api.wunderground.com/api"
    },
    {
      "path":"/search",
      "proxyUrl": "http://autocomplete.wunderground.com"
    }
  ]
}

weather.service.ts

import {Injectable, Inject} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class WeatherService {
        http: any;
        searchUrl: any;
        apiKey: string;
        conditionsUrl: string;
    static get parameters(){
        return [Http];
    }

    constructor(http){
        this.http = http;
        console.log('Service Connected : )');
        this.apiKey = '1e4420a89011eef4';
        this.conditionsUrl= 'http://api.wunderground.com/api/'+this.apiKey+'/conditions/q';
        this.searchUrl='http://localhost:8100/search/aq?query=';
    }

    getWeather(city, state){
        return this.http.get(this.conditionsUrl+'/'+state+'/'+city+'.json')
        .map(res => res.json());
    }

     searchCities(searchStr){
        return this.http.get(this.searchUrl+''+searchStr)
           .map(res => res.json());
    }
}

weather.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { OnInit } from '@angular/core';
import { WeatherService } from '../../services/weather.service';

@Component({
  selector: 'page-weather',
  templateUrl: 'weather.html',
  providers: [WeatherService]
})
export class WeatherPage {
    results: any;
    searchStr: any;
    weather: any;
    state: string;
    city: string;

  weatherService : WeatherService;
  static get parameters(){
    return [[WeatherService]];
  }

  constructor(weatherService) {
    this.weatherService = weatherService;
    this.city = 'Istanbul';
    this.state = '';
    this.searchStr;
    this.weather;
    this.results;
  }

  ngOnInit(){
    this.weatherService.getWeather(this.city, this.state)
    .subscribe(weather => {
      //console.log(weather);,
      this.weather = weather.current_observation;
    })
  }

  getQuery(){
        this.weatherService.searchCities(this.searchStr)
    .subscribe(res => {
      //console.log(weather);
      this.results = res.RESULTS
     console.log(this.results);
    })
  }
}

weather.html

<ion-header>
  <ion-navbar>
    <ion-title>Weather Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="body">
  <ion-grid *ngIf="weather">
    <ion-row>
      <ion-col width-100>
        <ion-list>
          <ion-item>
            <ion-label fixed>Enter City</ion-label>
            <ion-input (keyup)="getQuery()" [(ngModel)]="searchStr" type="text"></ion-input>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col width-50 offset-25>
        <h2 class="location">{{weather.display_location.full}}</h2>
        <div class="icon"><img src="{{weather.icon_url}}"></div>
        <h3 class="desc">{{weather.weather}}</h3>
        <h1 class="temp">{{weather.temp_c}}&deg;</h1>
      </ion-col>
    </ion-row>
      <ion-row>
      <ion-col width-100>
        <ion-list>
          <ion-item>
            <strong>Temp: </strong>{{weather.temperature_string}}
          </ion-item>
          <ion-item>
            <strong>Relative Humidity: </strong>{{weather.relative_humidity}}
          </ion-item>
          <ion-item>
            <strong>Dewpoint: </strong>{{weather.dewpoint_string}}
          </ion-item>
          <ion-item>
            <strong>Visibility: </strong>{{weather.visibility_mi}}
          </ion-item>
          <ion-item>
            <strong>Wind: </strong>{{weather.wind_mph}} Mph
          </ion-item>
          <ion-item>
            <strong>Wind Direction: </strong>{{weather.wind_dir}}
          </ion-item>
          <ion-item>
            <strong>Heat Index: </strong>{{weather.heat_index_string}}
          </ion-item>
          <ion-item>
            <strong>Last Updated: </strong>{{weather.observation_time_rfc822}}
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

The issue encountered can be viewed here. https://i.stack.imgur.com/G2KeM.png

While attempting to resolve the problem of "adding proxies to ionic.config.json", unfortunately, it remains unresolved.

Answer №1

After much persistence, I was able to solve the issue by installing cordova and adding 'cordova plugin add cordova-plugin-whitelist'. In the project's index.html file, I made sure to include:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval' 'unsafe-inline' *; object-src 'self'; style-src 'self' 'unsafe-inline'; media-src *">

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

Testing the Window beforeunload event method in an Angular unit test: A guide

Currently, I am actively involved in a project using Angular 8. One of the features I implemented was to show a confirm prompt when a user tries to navigate away from the site. This functionality was added by integrating the following function into my com ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

Extract the JSON array data from the Service and process it within the Component

When passing a response from the Service to the Component for display on the UI, each value needs to be parsed and stored in a variable. This can be achieved by extracting values such as profileId, profileName, regionName, etc. from the response. [{"profi ...

Minimize overlap across both projects

One scenario is having two projects that utilize a lot of the same components. How can we minimize redundancy between them? Is there a way to make them shareable? Perhaps leveraging webpack could be the solution? ...

Angular 2 Return {responseBody: "assigned variable with [object Object]"}

In my Angular 2 application, I am encountering an issue where I am sending a variable from a service to a component. In the template, the variable appears as expected, however, when attempting to send this variable to a PHP script using POST, I receive [ ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

When using the TypeScript && operator, the resulting type is not determined by the second operand

Several past discussions on SO have touched upon the concept that the inferred type from && is based on the last expression. TypeScript’s failure to detect union type with an && operator Uncovering the reason behind the && opera ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Error encountered with Angular Static Injector Provider when extending another injectable component

I am currently working on an API based service setup that is structured as follows: @Injectable() export class ApiBaseService { constructor( private http: HttpClient, _configuration: ConfigurationService ) { this.apiUrl = _ ...

How is it possible for passing a number instead of a string to not result in a compilation error?

Here is some code that has caught my attention. It involves passing a number to a function that expects a string. const getGreeting: Function = (name: String): String => { return `hello, ${name}`; }; const x: number = 2 console.log(getGreeting(x)) ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Angular 7 - Customize Mat-select-value color depending on a specific condition

One issue I am facing is changing the color of a selected value in a mat select based on a condition. This change should be visually apparent to the user. Although accessing mat-select-value from the styles is possible, implementing a condition using ng-cl ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

What is the best way to pass down SectionList prop types in TypeScript when using React?

I am working on creating a wrapper for SectionList in React Native that needs to accept all the standard props of SectionList along with some custom ones. How can I set up typescript to accommodate this? Here is what I have tried: import React from &apos ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...