Friday, March 31, 2017

Developing Nativescript app with Local API

This may be a silly question and I am very new to NativeScript. I have a sample project up. Trying to do a simple get request to a local api. This is a website setup on my local dev machine for:

http://test-api.dev/api/v1

I am trying to access an endpoint on my local API and it does not seem to return ANYTHING. But I can change the API endpoint to something that is not a local API and sometimes it return stuff.

The API is a Laravel/PHP api and I can confirm it is infact returning valid json, so I don't think the API is the problem. Here is my file.

var config = require("../../shared/config");
var fetchModule = require("fetch");
//var http = require("http");
var ObservableArray = require("data/observable-array").ObservableArray;

function GroceryListViewModel(items) {
    var viewModel = new ObservableArray(items);
    viewModel.load = function() {
        // http.getJSON(config.apiUrl + "events").then(function(result) {
        //  console.log(JSON.stringify(result));
        // }, function(error) {
        //  console.error(JSON.stringify(error));
        // });

        return fetch(config.apiUrl + "events", {
                headers: {
                    //"Authorization": "Bearer " + config.token
                    "Content-Type": "application/json"
                }
            })
            .then(handleErrors)
            .then(function(response) {
                console.log(response);
                return response.json();
            }).then(function(data) {
                console.dump(data);
                data.forEach(function(event) {
                    viewModel.push({
                        name: event.name,
                        id: event.id
                    });
                });
            });
    };

    viewModel.empty = function() {

        while (viewModel.length) {
            viewModel.pop();
        }
    };
    return viewModel;
}

function handleErrors(response) {
    if (!response.ok) {
        console.log(JSON.stringify(response));
        throw Error(response.statusText);
    }
    return response;
}

module.exports = GroceryListViewModel;

Please go easy on me, definitely seeking help on this though. Thank you all in advance.



via devcflynn

Advertisement