简体   繁体   中英

RESTful Crud MEAN.js routing

I am pretty new to the MEAN stack and I am currently using mean.js to structure my app. I am currently playing around to see how the routing works in Express and Angular.

One of my server routes:

app.route('/api/projects/:projectId')
    .get(users.requiresLogin, projects.read)
    .post(users.requiresLogin, projects.apply)
    .put(users.requiresLogin, projects.hasAuthorization, projects.update)
    .delete(users.requiresLogin, projects.hasAuthorization, projects.delete);

I am require a user authentication before any type of request toward this specific route and my users.requireLogin code is:

exports.requiresLogin = function(req, res, next) {

  if (!req.isAuthenticated()) {
    return res.status(400).send({
      message: 'User is not logged in'
    });
  }

  next();
};

Currently for my client side route I have

.state('projects.view', {
        url: '/:projectId',
        templateUrl: 'modules/projects/client/views/view-project.client.view.html',
        controller: 'ProjectsController',
        controllerAs: 'vm',
        resolve: {
          projectResolve: getProject
        },
        data: {
          pageTitle: 'Project {{ projectResolve.name }}'
        }

and finally the resolve for the client side route is

getProject.$inject = ['$stateParams', 'ProjectsService'];

  function getProject($stateParams, ProjectsService) {

    return ProjectsService.get({
      projectId: $stateParams.projectId
    }).$promise;
  }

Everything is working as expected except when the user isn't authenticated, I want to redirect him. Currently when I am accessing the specific route, nothing is really happening and I just get a message in the console.

angular.js:12011 GET http://localhost:3000/api/projects/57f86cfc2e363838211b19c5 400 (Bad Request)

I guess my question is, how do I catch the case where a user isn't logged in so I can redirect him to the login page?

Ah nevermind. Dug a little further in, seems like mean.js automatically handles redirection based on the error code returned. I should have returned a 401 to redirect to login.

angular.module('core').factory('authInterceptor', ['$q', '$injector',
  function ($q, $injector) {
    return {
      responseError: function(rejection) {
        if (!rejection.config.ignoreAuthModule) {
          switch (rejection.status) {
            case 401:
              $injector.get('$state').transitionTo('authentication.signin');
              break;
            case 403:
              $injector.get('$state').transitionTo('forbidden');
              break;
          }
        }
        // otherwise, default behaviour
        return $q.reject(rejection);
      }
    };
  }
]);

You can use Express#redirect Please check right version of Express before using it.

exports.requiresLogin = function(req, res, next) {

    var message =  'User is not logged in';

    if (!req.isAuthenticated()) {
        res.redirect('/login?nologin=' + message);
    }else{
        next();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM