I'm building an Ionic app and trying to use Laravel 5 as my API. I've got the a basic user signin/signup/forgot/reset UI in place and am learning how to use ngResource, but in order to test this I want to hit the localhost Laravel is running on.
Ionic serve is on localhost:8100 and Laravel's artisan serve is on localhost:8000. From what I've read I need to use an interceptor to gain access to the API from my app, so I set up an interceptor that checks for '/api' and uses localhost:8000, otherwise it will pull resources from the default localhost:8100.
angular.module('project.app.test', ['ngResource'])
// Application configuration
.constant('ConfigSettings', {
ver: '0.1.0',
env: 'dev',
host: 'localhost',
port: '8000',
})
// Interceptor
.factory('API', ['ConfigSettings',
function (ConfigSettings) {
var service = {
request: function (config) {
if (config.url.indexOf("/api") > -1) {
config.url = ConfigSettings.host + ':' + ConfigSettings.port + config.url;
}
return config;
}
}
return service;
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('API');
}])
// RESTful API using ngResource
.factory('User', ['$resource', function ($resource) {
return $resource('/api/user/:id');
}])
// Create New User
.controller( 'SignupController', [ '$scope', '$state', 'User',
function( $scope, $state, User ) {
var self = this;
$scope.postData = {};
$scope.createNewUser = function() {
console.debug( $scope.postData );
var user = new User($scope.postData);
user.$save();
//$state.go( 'login.index' );
};
} ] )
That would hit my Laravel test API endpoint:
Route::group( [ 'prefix' => 'api' ], function ()
{
Route::get( 'user/{id}', function ( $id )
{
return "Hello User {$id}";
} );
Route::any( 'user', function ()
{
return 'Hello Any';
} );
} );
This almost works except I get a cross-site scripting error, which I should have guessed would happen.
Is there a better way to implement this so the mobile app can use Laravel's RESTful API during development? If not how do you navigate around the cross-site scripting error? It seems like people are creating Ionic apps using Laravel as the API, but I can't find any examples of how they are implemented.