Can't HTTP get JSON from localhost?

Hello,

I am hosting a local server using Ruby on Rails and using Ionic as my frontend.

My home.ts file is as follows:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BoardPage } from '../board/board';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  boardPage = BoardPage;
  boardnames: any;
  
  constructor(public navCtrl: NavController, public http: Http) {
	this.http.get('http://localhost:3000/boards/index').map(res => res.json()).subscribe(data => {
		console.log(JSON.stringify(data));
		this.boardnames = Object.keys(data);
	},
    err => {
		console.log(Object.keys(err));
        console.log("Oops!");
    });
  }

}

The ionic server console prints out that there is an error.
More specifically:
ionicConsole

My Rails controller is as follows:

class BoardsController < ApplicationController
	def new
	end
	
	def create
	end
	
	def index
		string = '{"boardname":
			[{
				"board": "name",
				"board2": "name2"
			}]
			}'
		render json: JSON.parse(string)
	end
end

However, the Ruby server console gives me an HTTP: 200 OK status code, and accessing the site in a web browser gives me this:

My Ionic application works with other websites that provide JSON arrays, however. Just not when I use my local server. So what is going on?

In an Ionic app, “localhost” is the device. Are you running this server on port 3000 of the device?

I am running Rails at Port 3000, and Ionic at 8100, as per the defaults.

I should also add that I have deployed on device and tried to connect to my computer’s IP as the server. No such luck in getting the JSON array.

I have also used HTTP GET testing sites that are successfully able to get the JSON object from my local server, so the problem is definitely in Ionic.

Have you eliminated CORS as a source of problems?

Indeed, it appears CORS was the issue!

I fixed this by installing a Google Chrome extension called allow-control-allow-origin and activating it, then opening my ionic app in Chrome.

This is only a temporary fix for development, and I assume I will have to set up CORS headers on the Rails side of my project when I move to production, but this works for now.

Thank you!

Have you try ionic 3 build in proxy function?
You can edit “ionic.config.json” in root of project file.
Like below example, all http call to “/api/*” will auto redirect to localhost.

{
  "name": "aaa",
  "app_id": "com.aaa",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://localhost:3000/"
    }
  ],
  "type": "ionic-angular"
}