標籤:
- router.post(‘/register‘,function(req,res,next){
- var restResult = new RestResult();
- var mobile = req.body.mobile;
- if (!/1\d{10}/.test(mobile)){//手機號碼格式校正
- restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
- restResult.errorReason = "請填寫真確的手機格式";
- res.send(restResult);
- return;
- }
- var password = req.body.password;
- if(!password || password.length < 6){//密碼長度校正
- restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
- restResult.errorReason = "密碼長度不能少於6位";
- res.send(restResult);
- return;
- }
-
- //findOne方法,第一個參數數條件,第二個參數是欄位投影,第三那個參數是回呼函數
- UserEntity.findOne({mobile:mobile},‘_id‘,function(err,user){
- if(err){//查詢異常
- restResult.errorCode = RestResult.SERVER_EXCEPTION_ERROR_CODE;
- restResult.errorReason = "伺服器異常";
- res.send(restResult);
- return;
- }
-
- if (user){//手機號登入
- restResult.errorCode = RestResult.BUSINESS_ERROR_CODE;
- restResult.errorReason = "手機號登入";
- res.send(restResult);
- return;
- }
-
- var registerUser = new UserEntity({mobile:mobile,password:password});
- //調用實體的執行個體的儲存方法
- registerUser.save(function(err,row){
- if(err){//伺服器儲存異常
- restResult.errorCode = RestResult.SERVER_EXCEPTION_ERROR_CODE;
- restResult.errorReason = "伺服器異常";
- res.send(restResult);
- return;
- }
-
- res.send(restResult);//返回成功結果
-
- });
-
- });
-
- });
-
-
-
- //登陸路由
- router.post(‘/login‘,function(req,res,next){
- var restResult = new RestResult();
- var mobile = req.body.mobile;
- if (!/1\d{10}/.test(mobile)){//手機號碼格式校正
- restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
- restResult.errorReason = "請填寫真確的手機格式";
- res.send(restResult);
- return;
- }
- var password = req.body.password;
- if(!password){
- restResult.errorCode = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
- restResult.errorReason = "密碼不可為空";
- res.send(restResult);
- return;
- }
-
- UserEntity.findOne({mobile:mobile,password:password},{password:0},function(err,user){
- if(err){
- restResult.errorCode = RestResult.SERVER_EXCEPTION_ERROR_CODE;
- restResult.errorReason = "伺服器異常";
- res.send(restResult);
- return;
- }
-
- if(!user){
- restResult.errorCode = RestResult.BUSINESS_ERROR_CODE;
- restResult.errorReason = "使用者名稱或密碼錯誤";
- res.send(restResult);
- return;
- }
-
- restResult.returnValue = user;
- res.send(restResult);
-
- //更新最後登陸時間
- UserEntity.update({_id:user._id},{$set: {lastLoginTime: new Date()}}).exec();
-
- });
-
- });
-
- module.exports = router;
RestResult.js(統一返回資料格式)檔案內容如下:
[javascript] view plain copy
- var RestResult = function(){
- this.errorCode = RestResult.NO_ERROR ;
- this.returnValue = {};
- this.errorReason = "";
- };
-
-
-
- RestResult.NO_ERROR = 0;//無錯誤
- RestResult.ILLEGAL_ARGUMENT_ERROR_CODE = 1;//無效參數錯誤
- RestResult.BUSINESS_ERROR_CODE = 2;//業務錯誤
- RestResult.AUTH_ERROR_CODE = 3;//認證錯誤
- RestResult.SERVER_EXCEPTION_ERROR_CODE = 5;//伺服器未知錯誤
- RestResult.TARGET_NOT_EXIT_ERROR_CODE = 6;//目標不存在錯誤
-
- module.exports = RestResult;
手機號碼格式校正