2016-07-23 65 views

回答

0

退房的mean.js樣板: https://github.com/meanjs/mean

你會看到他們是如何很快做到這一點:

moduleName.client.controller.js會發出HTTP調用,使用HTTP注入。這裏正在從/modules/users/client/controllers/authentication.client.controller.js進行呼叫的例子(有一些編輯的代碼,使其更容易看到你在找什麼):

AuthenticationController.$inject = ['$scope', '$state', '$http', 'Authentication']; 

function AuthenticationController($scope, $state, $http, Authentication,) { 
    ... 
    vm.authentication = Authentication; 

    $http.post('/api/auth/signup', vm.credentials).success(function (response) { 
    // If successful we assign the response to the global user model 
    vm.authentication.user = response; 

    }).error(function (response) { 
    vm.error = response.message; 
    }); 
} 

現在,這個調用發佈到「/ API /認證/註冊」。處理這一路線的文件位於/modules/users/server/routes/auth.server.routes.js

modules.exports = function(app) { 
    var users = require('../controllers/users.server.controller'); 
    ... 
    app.route('/api/auth/signup').post(users.signup); 
} 

正如你可以看到,路由(URL)匹配您從客戶端控制器那叫一個。由於來自控制器的$ http呼叫是$http.post(),路由條目必須匹配。你可以看到它在上面。 上面通過的參數users.signup指的是另一個文件中的函數:/modules/users/server/controllers/users/users.authentication.server.controller.js。這是users模塊驗證部分的主控制器。現在,這個文件中,我們可以看到signup功能導出:現在

/* note: there are global variables here, see below */ 
exports.signup = function (req, res) { 
    // For security measurement we remove the roles from the req.body object 
    delete req.body.roles; 

    // Init user and add missing fields 
    var user = new User(req.body); 
    user.provider = 'local'; 
    user.displayName = user.firstName + ' ' + user.lastName; 

    // Then save the user 
    user.save(function (err) { 
    if (err) { 
     return res.status(400).send({ 
     message: errorHandler.getErrorMessage(err) 
     }); 
    } else { 
     // Remove sensitive data before login 
     user.password = undefined; 
     user.salt = undefined; 

     req.login(user, function (err) { 
     if (err) { 
      res.status(400).send(err); 
     } else { 
      res.json(user); 
     } 
     }); 
    } 
}); 
}; 

,很多是怎麼回事,但我們可以把它分解。

req變量是通過$ http傳遞的發佈請求。變量res是客戶期望收到的回覆。 請注意vm.credentials如何通過$http.post('/api/auth/signup/', vm.credentials)?這是綁定到req.body並可能由您的服務器控制器訪問。

因此在本例中,req.body是在服務器上創建新用戶所需的數據。這是通過使用mongoose來完成的,它有一個名爲User的模式。通過在控制器頂部聲明全局變量來訪問:

var mongoose = require('mongoose'), 
    User = mongoose.model('User'); 

您可以看到上面實例化了一個新用戶。它通過貓鼬電話.save()保存。

最後,您的服務器功能應該使用傳遞給函數的res變量來響應客戶端的請求。怎麼看,一旦用戶創建成功,函數調用

res.jsonp(user); 

這是success()到客戶端,它接受響應並將其綁定到一個局部變量vm.authentication.user

希望這有助於!

+1

Thanks mtro。雖然它不能完全解決問題,但它有很大幫助。 – SumantMishra

相關問題