Angular js and Laravel http get params - http

I am totally new to angularjs and i am practicing.
I am a bit stuck with the following, i have a profile page what loads the users details, and i do not really know how to show it, problem is im stuck with the logic.
I created 2 routes for it
Route::get('/(:any)', array('as' => 'profile', 'uses' => 'user#profile'));
Route::get('/details/(:any)', array('as' => 'profile', 'uses' => 'user#details'));
So the url actually looks like this: http://mysite.com/username
So my logic works like this, this route
Route::get('/(:any)', array('as' => 'profile', 'uses' => 'user#profile'));
Returns the profile view
this route would fetch the users data in json
Route::get('/details/(:any)', array('as' => 'profile', 'uses' => 'user#details'));
and what i am stuck with is this
I load the view, http://mysite.com/username i get the profile page,
Laravel view load
public function get_profile($username = '')
{
return View::make('user.profile');
}
Loading the json
public function get_details($username = '')
{
$users = User::where_username($username)->get();
return Response::eloquent($users);
}
angularjs controller
function profileCtrl($scope, $http) {
//here get the url first segment somehow
// and pass it to the get
// example
// urlSegment = username
$http('details/' + username ).success(function(data){
$scope.users = data;
console.debug(data);
});
}
So my question is, am i doing this okay, or im completly not on the right track.
Could someone show me an exampe for this?
Thank you
EDIT
To be more specific, i am trying to create a restful api with angularjs and laravel but im a bit stuck with it. What i do not understand is the routing logic.
example.
mysite.com/username, What type of route logic i need to build up to fetch the data?
Because i explained above, i created 2 routes for it, and i think thats not good.

i am trying to create a restful api with angularjs and laravel but im a bit stuck with it. What i do not understand is the routing logic.
Laravel provides a number of convient ways to create a restful API. It should be noted Laravel is "the restful api" and AngularJS is the client that will use the API to show the results (i.e. be the user front end).
Laravel 4 refers to 'Resource Controllers' to help you build a restful API. Using this picture, you can see how the controller should be laid out, and what each command is specifically required to do:
Just replace "photos" with "user" and that is how the controller will be laid out. If you are using Laravel 4 you can generate a resourceful controller using Artisan:
php artisan controller:make UserController
and it will add each of the functions above ready to go.
Laravel 3 refers to 'Restful Controllers' - but the principle is the same.
If you are interested - Nettuts has a great free tutorial on creating a Restful API with Laravel 4 from scratch. If you follow this tutorial - you will have a full restful API for your user class. It goes into much more detail than is possible in this answer.
For Laravel 4 your routes will be just one line of code:
Route::resource('user', UserController);
Then you will run the follow artisan commands
php artisan controller:make UserController
php composer.phar dump-autoload
Then your User Controller will be ready to go, with all the functions scaffold, and all you need to do is put some base logic in.
edit: I just found another tutorial that explains Laravel 4 resource controllers a bit further.

Angular is a client-side framework running only in the browser. So you simply cannot create a restful API with it. A restful API always runs on the server only, so Laravel should work for that.
The way Angular is meant to be used is that the client requests the content as JSON from a restful API running on the server (with the $http module) and then the HTML is built on the client-side. See what-is-the-point-of-angularjs-routes? I also highly recommend the official tutorial.

Related

Storing user data with ASP.NET 5.0 without OpenID Connect and Razor pages

In ASP.NET 5.0 I would like to implement a simple cookie authentication and store the user data safely in the database.
The cookie authentication works fine, this way I am able to implement on the frontend side all the user-related functionality in the SPA so there are no navigations outside the Angular app. (This way there is no redirection to an external Razor page to implement for example the login functionality.)
However, I have now the problem of storing safely user data on the server-side. (For example, hashing the password correctly.) If I would use ASP.NET Identity, it would solve all the storing issues out of the box. The problem is, that all the examples show only implementations with Razor pages and OIDC.
Is there a possibility to use the ASP.NET Idenitity only for storing the user data without using the Razor pages and OIDC?
I don't want to use the embedded OIDC implementation of ASP.NET, because I have a tiny Angular SPA, and all the redirections from/to the Razor pages of Identity make the user experience bad. On the other hand, if I would use the Razor pages of Identity I would need to style them to the same as my Angular application, which seems to be a smelly code duplication to me. (Among others I also would need to apply the material design on them.)
The answer is yes, there is a possibility for this!
First of all Identity should be added to the services following way:
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128)
.AddEntityFrameworkStores<ApplicationDbContext>();
Note that not AddDefaultIdentity is used, because AddDefaultIdentity involves the default Razor pages as well, in my case I don't want to have them.
This way the UserManager is available and it can be injected in the constructor and it can be used for creating users in the DB. (The UserManager handles the safe storage of user data.)
However, this way when there was an unauthorized or a forbidden API call, the backend tried to redirect to some default routes that did not exist. So following configuration needed to be added as well:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = (context) =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = (context) =>
{
context.Response.StatusCode = 403;
return Task.CompletedTask;
};
});
Using the above approach services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(..)
needed to be removed.

How to configure emberjs routes in SpringMVC?

We have an Ember frontend and Spring Boot backend.
When Ember runs standalone on port 4200 and the Spring Boot backend on 8080, then everything works. But this scenario is somewhat unusual for production environments, not only because of CORS problem. The URL of the backend must be known already on build time (!) of the Ember application, because it's integrated within the compiled ember app. This is not possible for many projects. Therefore, we want to integrate the frontend Ember App in the Spring Boot backend, which is usual for e.g. SPA with AngularJS.
The Ember app (from /dist) is thus copied to src/main/resource/static. After adjusting the rootURL and API.host with the Ember app that works very well.
The problem arises now, when a manual reload for an URL is made in the browser. Such a URL is now an Ember route. The http-request arrives at the Spring Boot backend which don't knows the route and we got a 404 error.
How should SpringMVC (as part of the Spring Boot backend) answers the httpRequest for such a route, so that the Ember app continue their work and handle the request ?
HTML Page request (by browser)
http://host/springBootAppContext/index.html => src/main/resource/static/index.html (ember app)
REST API request (by Ember App)
http://host/springBootAppContext/users => RESTController mapped for /users
Ember Routing (by Ember App)
http://host/springBootAppContext/user-list => ???
You can't provide a normal Spring MVC #Controller class because the ModelView response is interpretet as user-list.html or similar which doesn't exist
after tests with different solutions I came up with a really simple one.
Provide a normal, non-REST controller with request mappings for every route defined by the ember app. Every such request have to be answered with the view name of the ember app start page (index.html in most cases). The browser loads that html page and starts the containing ember app. The ember app detects the route (because the route was part of the http request) and work according all specified route configurations (template, model, controller).
No 404 NotFound any more.
#Controller
public class EmberRouteController {
public static final String INDEX = "index.html";
#RequestMapping(value = "/ember-route-1", method = RequestMethod.GET)
public String emberRoute1() {
return INDEX;
}
#RequestMapping(value = "/ember-route-2", method = RequestMethod.GET)
public String emberRoute2() {
return INDEX;
}
}
The previous answer helped me a lot. But I was still thinking of better solution than creating backend APIs for each route. And I feel the better solution would be to put '#' in before ember route then ember routes serves the request rather than going to the backend server.
Router.reopen({
location: 'hash'
});
Ex: http://localhost:8008/#/first
Here first is my route. And I have put # in the URL, now reload of the page is working.
Hope this will help.

Symfony2 and WebRTC, routing issue

So I use Pubnub for WebRTC in my Symfony 2 application, and all works well, apart from the showing of videos of other users. What happens is that when a user connects, an url gets generated like this one:
mediastream:http://www.domain.com/cd024a62-02fa-42eb-8f52-621074ea887e
These url's are temporary, and the only purpose is to serve as a way to connect video streams. After the WebRTC session the do not exist anymore and they are impossible to predict.
Since the Symfony router cannot find a route to 'http://www.domain.com/cd024a62-02fa-42eb-8f52-621074ea887e', the stream is never showed (www.domain.com is the url to the symfony application in this example).
What I could do is adapt the exisiting scripts so that all video streams look like 'http://www.domain.com/video/cd024a62-02fa-42eb-8f52-621074ea887e', but in that case any route with prefix /video/ should be left alone by Symfony.
Any ideas?
In the end I found a solution. As a last routing rule I added:
display_blob:
defaults: { _controller: Bundlename:Main:blob }
path: /{blob}
Then I created a function in the Main controller:
public function blobAction(Request $request)
{
$path = $request->getUri();
return $this->render($path);
}
Of course I need to do some filtering of the URL itself and check if it really is a stream, but for now I am happy it works.

Google Cloud Endpoints (JAVA): return html content

How can i return html content with Google Cloud Endpoints using JAVA?
I'd like to return an html page after a user call a REST API. It is possible?
Endpoints aren't designed to return web pages. You can look at endpoints as a framework for defining remote procedures or a RESTful API. i.e. something you'd call from JS or a mobile platform. To serve a web page on App Engine in Java you should use an App Engine servlet similar to this example.
You can return it as a string, assuming you had cached the HTML page somewhere accessible (remember, appengine has no local file storage). Within your endpoints function, you can access datastore, memcache, cloudstorage, etc...
While I do echo the other poster in saying this is not the use-case endpoints is really meant to target, the point is, endpoints is a great way to make an API with automatic generation of client libraries for multiple platforms. Do use endpoints for your API, but be sure it's an API function and not just HTML file serving, for which there are better patterns.
If you are using this pattern to serve HTML partials for an ajax-style dynamic-replacement div in a web app, this is fine, although if these partials are not needing processing or can be defined at deployment time, rather than being put() and get()'d from datastore, for example, then it's best to simply link them in as static resources using the appengine-web.xml / app.yaml (depending on java or python/go/php)
I hope this has helped you think more about your use-case.
You can redirect browser to new page after server responded to call:
gapi.client.yourapp.yourmethod().execute(function(resp) {
console.log(resp);
if (resp.page){
location = 'http://yourappid.appspot.com/' + resp.page + '?userid=123';
}
});
But you must take care somehow about not losing your context. For example transfer userid as done in above code.

Html.BeginForm in WebApi - routing

I have a Web API project as part of my solution (also containing an MVC4 project) and within the Api project I am trying to post a form to the Values controller Post method (from a view also within the Api project).
Using Html.BeginForm() or Html.BeginForm("Post", "Values") posts to /Values/Post but I need it to go to /api/Values/Post
Any idea which overload or settings I need to post to the correct location?
I can hit all the action methods fine from fiddler (e.g. localhost/api/values).
You would need to use BeginRouteForm as link generation to Web API routes always depends on the route name. Also make sure to supply the route value called httproute as below.
#using (Html.BeginRouteForm("DefaultApi", new { controller="Values", httproute="true" }))
The API controller uses a different route to the default. It's supposed to be consumed from JS (AJAX) rather than a real form post so there's no obvious support for it in HtmlHelpers. Try:
Html.BeginForm("values", "api")
This would trick it into thinking "values" is the action and "api" is the controller. "Post" is inferred from the http method.

Resources