1

I'm making a AngularJS app and I'm using a Slim API. I use my API to get data from my DB.

I was testing my app and I noticed something. I have my app in my localhost, but in a server to and they use the exact same code. I use this code to call my API:

angular.module('appDatabaseCtrl', [])
.controller('databaseCtrl', ['$scope','$routeParams', '$http', '$log',
    function($scope, $routeParams, $http, $log){
        $scope.testDatabaseItems = function(){
            $http.get('/api/items').success(function(data) {
                $log.info("succes!");
                $log.log(data);
            })
            .error(function (data, status){
                $log.error("error!");
                $log.log(data);
            });
        };
        $scope.testDatabaseItemById = function(){
            $http.get('/api/items/' + $scope.id).success(function(data) {
                $log.info("succes!");
                $log.log(data);
            })
            .error(function (data, status){
                $log.error("error!");
                $log.log(data);
            });
        };
    }
]);

Here is my "index.php" file in my Slim API:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

//nécessite Slim
require 'vendor/autoload.php';


//Instancie une app de Slim
$app = new \Slim\App;

//Associe type de requête avec fonction et paramêtres
$app->get('/items', 'getItems');
$app->get('/items/{id:\d+}', 'getItemById');

//Démarre l'application
$app->run();

// Accès à la base de données
function DB_Connection() {  
    $dbhost = "localhost";
    $dbuser = "kevdug_angularjs";
    $dbpass = "*****************";
    $dbname = "angularjs";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

function getItems() {
    $sql = "select * FROM aj_items";
    try {
        $db = DB_Connection();
        $stmt = $db->query($sql);  
        $list = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($list);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

function getItemById(Request $request, Response $response, $args) {
    $id = $args["id"];
    $sql = "select * FROM aj_items WHERE id=".$id;
    try {
        $db = DB_Connection();
        $stmt = $db->query($sql);  
        $list = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($list);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

?>

If I use the "testDatabaseItems" function in my app on my server, it perfectly works, but when I try using it in my localhost, I get an 404 error:

"NetworkError: 404 Not Found - http://localhost:8080/api/items"

I know that the reason why I get a 404 error page is simply that the address should be:

localhost:8080/angularjs/api/items

What I want is that in my localhost version, it use the good path but that I don't need to have a different code for my localhost version and my server version.

An other strange thing is that If I go to http://kevdug.webfactional.com/api/items, I get my json object like I expect, but in my localhost, I need to got to "(my localhost address)/api/index.php/items". I need to specify the "index.php" file for some reason and I would like to not need to do that.

1 Answer 1

1

Regarding the remote server and local server configuration, just use a simple boolean.

// the uri-base is for both remote and local server the same
$uri = 'http://localhost:8080/';

expecting uri of the current file on remote server to be different than file-uri on local server. e.g, on remote server it is /www/site/class.php and on local server it is c:/php/class.php if that doesnt work, use another pc-specific fingerprint, or just put a file on the remote-server and check if e.g., file exists.

example code

if(strpos(__FILE__, 'c:/php/') === 0) {

  # is local config
  $uri .= 'angularjs/api/items';
}
else {

  # is remote config
  $uri .= 'api/items';
}
Sign up to request clarification or add additional context in comments.

3 Comments

The thing is that I need to do it in my javascript file, NOT in a php file. Plus, you answer is a bit to technical for me, could you make it more simple to understand?
hi Kévin, in your javascript-file it should be pretty easy to achieve. Here you can just read the domain-name by window.location or something to check if the location is localhost (is local, choose local url) or not localhost (is remote, choose remote url).
Thanks, your idea is so simple yet perfect for my situation, can't believe I didn't think about it. I used a if statement to put the path to the API in a var that I just always use every time I need to call my API. I just add the index.php file in the path since I noticed that if I use 'api/...' insted of "/api/..." it finds the wright api folder... Why si that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.