2015-05-23 115 views
0

我最近開始學習MEAN堆棧,並遇到一個問題。我試圖從角度發送一個$ http.get請求到我的本地服務器,但請求主體是未定義的。有什麼特別的是它在我的文章中沒有定義。我意識到這個問題可能是身體解析器,我花了幾個小時試圖找出解決辦法無濟於事。謝謝你的幫助!爲什麼我的請求是空的?

這裏是我的快件代碼:

var express = require('express'); 
var mongoose= require('mongoose'); 
var bodyParser=require('body-parser'); 
var http=require('http'); 
var db=mongoose.connect('mongodb://localhost:27017/checkIt'); 



var server = express(); 
var Schema= mongoose.Schema; 



server.use(bodyParser.urlencoded({ 
    extended: true 
})); 

server.use(bodyParser.json()); 


server.use(express.static(__dirname)); 



var UserSchema = new Schema({ 
    username: String, 
    password: String 
}); 

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


server.post("/checkIt/users",function(req,res){ 

    var newUser = new User({ 
     username: req.body.username, 
     password: req.body.password 
    }); 

    newUser.save(function(err,doc){ 
     res.send("inserted"); 
    }); 

}); 

server.get("/checkIt/users",function(req,res){ 
    console.log(req.body); 
    var userToCheck= new User({ 
     username:req.body.username, 
     password:req.body.password 
    }); 

    User.findOne({username: userToCheck.username, password: userToCheck.password},function(err,obj){ 
     res.send(obj); 
    }); 

}); 
server.listen(3000); 

這是我的LoginController在那裏我有我的GET請求:

angular.module('app') 
.controller('loginController',['$scope','$location', '$http',function($scope,$location,$http){ 


    $scope.checkIfUser = function(){ 
     var user={ 
      username:$scope.username, 
      password:$scope.password 
     }; 

     $http.get("http://localhost:3000/checkIt/users",user) 
      .success(function(response){ 
       if(response===""){ 
        console.log("User does not exist"); 
       } 
       else goToHome(); 
      }); 
    }; 

    var goToHome = function(){ 
     $location.path('/Home') 
    } 

}]); 

最後,我不知道這是否會幫助或沒有,但這個是我做我的$ http.post請求的代碼片段

$scope.signup = function(){ 
      createUser(); 
      console.log(user); 
      $http.post("http://localhost:3000/checkIt/users",user) 
      .success(function(response){ 
       console.log(response); 
      }); 
     }; 

回答

1

有沒有一個GET!這就是生活。沒有正文GET。現在解決問題。您想在服務器端使用req.query來訪問這些值。

在你需要對你的代碼略有變化的角度側(URL中發送的密碼是一件壞事):

$http.get('http://localhost:3000/checkIt/users', { 
    params: { username: $scope.username, password:$scope.password } 
}).success(... same as before); 
+0

謝謝你的回答。我結束了使用req.query來訪問值,因爲params給我不確定。我會仔細閱讀一下,找出原因和是的,不用擔心,這是爲了學習的目的,我將來不會在URL中發送密碼。謝謝您的幫助! –

+0

你說得對'關於req.query' - 抱歉。 'req.params'用於像'/ users /:userId'這樣的參數路由。 'req.params.userId'將包含用戶標識。我會解決我的答案。 –

0

的請求主體是不確定的,只是因爲你無法通過傳遞PARAMS一個GET請求,你可能想要改變你的路由名稱,並使用POST請求。

順便說一下,將您的API請求移動到UserService並將其注入到控制器中可能會更清潔,因爲您最終需要在其他位置重新使用它們。

相關問題