简体   繁体   中英

Working on a login with Hapi.js and Angularjs

Let me see if I get this, here are the Docs for hapi

I have this on the backend/hapijs/node side

server.route({
  method: 'POST',
  path: '/login',
  handler: function(request, reply) {
    USER: request.payload.user,
    PWD: request.payload.password,
    PLANTA: request.payload.planta,
    PLANGROUP: request.payload.plantgroup,
    START_DATE: request.payload.startDate
  }
});

and here the front-end

  .factory('LoginService', function($http, $q) {

    var defer = $q.defer();

    return {
      login: function(params) {
        $http.post('http://localhost:8000/login', {
          user: 'USRCP_HW',
          password: 'usrcp2012',
          planta: '6000',
          plantroup: 'E10',
          startDate: '2014-11-26'
        }).success(function(data) {
          console.log(data);
        }).error(function(data, status){
          console.log(data, status);
          defer.reject(data);
        });
        return defer.promise;
      }
    }

  });

and the controller, I am so confuse here

  .controller('LoginCtrl', function($rootScope, $scope, $stateParams, LoginService) {

    $scope.login = function() {
      LoginService.login($scope.params).then(function(params) {
        console.log('credentials', $scope.params, params);
      })
    };   
  });

and I am getting 2 errors in the console:

OPTIONS http://localhost:8000/login 501 (Unsupported method ('OPTIONS'))

and

XMLHttpRequest cannot load http://localhost:8000/login . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://127.0.0.1:8000 ' is therefore not allowed access. The response had HTTP status code 501.

so, what am I missing here ?

Well, your hapi route is invalid JavaScript, so I'm not sure how it would be running. You are getting the payload values correctly, using request.payload. You would need to change it to something like this:

server.route({
 method: 'POST',
  path: '/login',
  handler: function(request, reply) {
    var user = {
         USER: request.payload.user,
         PWD: request.payload.password,
         PLANTA: request.payload.planta,
         PLANGROUP: request.payload.plantgroup,
         START_DATE: request.payload.startDate
    };
    // do something with user object here
});

The OPTIONS method issue is because Angular is attempting to do CORS. Just make the POST path relative and it should resolve correctly to your server.

$http.post('/login', {
  user: 'USRCP_HW',
  password: 'usrcp2012',
  planta: '6000',
  plantroup: 'E10',
  startDate: '2014-11-26'
})

You would need to have your hapi server serving this Angular content as well, not opening it from your file system.

Hope this helps!

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