3

We want to get rid of an old Flex project, rebuilding it into HTML5. As a result of that we're building a proof of concept in Angularjs2 and want to integrate the services in the existing PHP Symfony 2 backend. But since Angular runs 'out of the box' with nodejs on localhost:3000 and the Symfony2 project runs on localhost:8888 I get session issues. Requests sent from the localhost:3000 get different PHPSESSID back in every single call while logged in, so the server doesn't remember the user.

What is the best way to approach this problem?

Can I run the Angularjs project from localhost:8888? If I try that it complains it's not running from localhost:3000.

enter image description here

5
  • Are you sure that angular reqieres nodeJs? As far as I know it simle frontend framework. Only angular library is required. Commented Jul 2, 2016 at 7:39
  • I think it can run on any server, in the end it's javascript. But the tutorials I've done so far all use node.js and use mock's for their requests. Commented Jul 2, 2016 at 7:46
  • I think you can use your Symfony2 framework as API to get data from DB etc. In your case you have already built a backend, do not see any reason to use nodeJs. Commented Jul 2, 2016 at 7:53
  • I tried that but then I get a js error that tell's me it wants to run from localhost:3000 Commented Jul 2, 2016 at 7:59
  • 1
    I'll add some steps how you can avoid NodeJs as answer, ok? Commented Jul 2, 2016 at 8:05

2 Answers 2

1

Let me show an example without NodeJs

Firs, you have to install NelmioCorsbundle and FosRestbundle, than configure them like

nelmio_cors:
    paths:
        '^/':
            origin_regex: true
            allow_origin: [ 'http://your-domain.com' ] << your frontend
            allow_headers: ['Origin','Accept','Content-Type']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts:
                - "^(http?://)?api\.your-domain.com?" << your backend as subdomain
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'

Write your general getter in your app.service (frontend)

yourApp.factory('appService', ['$http', '$q', '$localStorage',
  function($http, $q, $localStorage)
{
  var $this = {};

  $this.mainGetter = function(action, config) {
    var deferred = $q.defer();
    $http({
      method: 'GET',
      url: $this.domain + action,
      params: config
    }).then(function(data) {
      deferred.resolve(data);
    }, function(error) {
      deferred.reject(error);
    });
    return deferred.promise;
  };

  return $this;
}]);

then create an endpoint in your backend

/**
 * API Controller
 * @CFG\Route("/api")
 */
class ApiController extends FOSRestController
{
    /**
     * @CFG\Route("/get-something", name="get_smt")
     * @CFG\Method("GET")
     * @param Request $request
     * @return JsonResponse
     */
    public function getPostsAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $something = $em->getRepository('SomeRepo')->findAll();

        $serializer = $this->get('jms_serializer');
        return new JsonResponse([
            'isError' => 0,
            'data' => $serializer->serialize($something, 'json')
        ]);
    }
};

And finnaly get the data from your angular controller or service

  $this.getApiData = function(alias) {
    var deferred = $q.defer();
    appService.mainGetter('/get-something', {})
      .then(function(response) {
        var data = response.data;
        if (data.isError) {
          deferred.reject(data.error);
        } else {
          deferred.resolve(data.data);
        }
      });
    return deferred.promise;
  };
Sign up to request clarification or add additional context in comments.

6 Comments

Is it explicit necessary to use the NelmioCorsBundle and the FosRestBundle to integrate Symfony2 with AngularJS2? We have a REST service with hundreds of functions. It expects a GET or a POST and returns soap or json. I'de rather leave this service alone
I added a screenshot.
I think that is not necessary to use the NelmioCorsBundle and the FosRestBundle if you able to configure your backent to get calls from another domain or subdomain.
As I understand this is exactly what happens - your backend reject http calls from your frontrend am i right?
It's not the backend that's complaining (see screenshot above), it's Angular that says 'Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode'
|
0

Ok thank you, D.Dimitrioglo, for that last comment, 'It is just a notification, is not an error. do not pay your attention to this', so I didn't spend time on figgering out why my host was unsuported. I need nodejs though to compile the TypeScript I use into Javascript, so that was not it. Also I do not explicitly need NelmioCorseBundle and FosRestBundle. My problem is

  1. I had to do a proper npm clean/install in the root of my php project, instead of copy pasting it from my angularjs/ folder.
  2. the angular/router-depricated (routing the url to different pages in a project) conflicts with the Symfony2 routing functionality so when I removed the angular router it showed the right page and could run it from localhost:8888

After that my session was preserved after logged in! Thx for your comment it guided me in the right direction!

Comments

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.